{ yeah : 必须哒 } No place to place should record our youth?

11Aug/100

lua实现microtime扩展,提高math.randomseed力度

某个项目需要随机生成crypt相关的,当时用到randomseed是采用os.time(),果然与我考虑的一样,生成的随机很不理想,os.time()占一秒,跨越太大了,当然也考虑过利用闭包的模式,自增一个小数点,不过考虑到实用性,还是决定在原来的lua-mylib(现在改名为:lua-nix)中加入一个microtime,返回一个float数,增加了seed的跨越力度,这样重复的机会几乎没有,最后实现代码如下:

[cc lang='lua']
function generate_nonce()
--math.randomseed(os.time()) --seed力度不够
math.randomseed(nix.microtime()*1000000) -- better than before
return math.random()
end
[/cc]

扩展源码如下:
[cc lang='c']
……
#include
……
#define MICRO_IN_SEC 1000000.00
……
static int Lmicrotime (lua_State *L) {
struct timeval tp = {0};
if (gettimeofday(&tp, NULL)) {
lua_pushboolean(L, 0);
}
lua_pushnumber(L, (double)(tp.tv_sec + tp.tv_usec / MICRO_IN_SEC));
return 1;
}
……
[/cc]
具体可以参阅:http://alacner.com/pro/git/?a=summary&p=lua-nix

Posted by alacner

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

(required)

No trackbacks yet.