4 回答

TA貢獻1806條經驗 獲得超5個贊
你的程序那么短,返回0是正常的
我在自己的電腦上試了試,在調用clock()前用了Sleep(1000),結果就不一樣了
Sleep()是 Windows API,不要在你的程序里用
而且覺得,隨機數鐘子只要設一次就夠了,不應該每次設,
你這樣,在一段時間內(大約1毫秒)都會得到同樣的隨機數
clock返回的大約是毫秒級(不是處理器周期,你可以查CLOCKS_PER_SEC)

TA貢獻1831條經驗 獲得超4個贊
clock 計算的是從程序運行到執行clock時的時間間隔。
重復啟動程序,時間還是 從程序運行到執行clock時的時間間隔。
這個數字不變,種子不變。你的隨機就不隨機了。
所以要用:
srand(time(NULL));
time(NULL) 是永遠在變的。種子變,隨機了。

TA貢獻1820條經驗 獲得超9個贊
The clock() function returns an approximation of processor time used by the program.
以上內容摘自 man 3 clock
返回接近程序使用的CPU時間 你拿這個做種子?
如果linux下 建議
GRand* g_rand_new (void);
Creates a new random number generator initialized with a seed taken either from /dev/urandom (if existing) or from the current time (as a fallback).
使用這個函數 直接使用操作系統提供的/dev/urandom 這個設備是根據環境噪聲產生的真(記得好像是)隨機數
如果沒有urandom就使用當前時間 具體這個時間精確到多少不知道
如果不用glib庫
就直接去讀/dev/urandom設備 這個做種子是最好了的
linux里面一般都用這個/dev/random 和/dev/urandom得到真隨機數 這個這個設備的種子是 通過中斷事件得到的 網卡 鍵盤 等設備的中斷是異步 產生的隨機數應該可以算作真隨機數了
不過這個只適應linux而且 程序環境必須是在有交換性 也就是外界必須提供中斷事件 而且如果熵池里面的隨機數用完了 讀取這個設備會造成程序阻塞 直到熵池里有新的隨機數
如果你的程序適應這種條件
可以使用glib 有交換環境 linux (一般不是特殊環境下都滿足)
建議直接使用這個方便的函數了
glib就是為了方便程序員 跨平臺跑程序的 在window下可以用
clock()函數沒什么好說的我直接把man里面note節翻譯給你看下
Note that the time can wrap around. On a 32-bit system where CLOCKS_PER_SEC equals 1000000 this function will return the same value approximately every 72 minutes.
每72分鐘會產生相同的值 (所以肯定是偽隨機數,不過可以達到一般程序要求了)
On several other implementations, the value returned by clock() also includes the times of any children whose status has been collected via wait(2) (or another wait-type call). Linux does not include the times of waited-for children in the value returned by clock(). The times(2) function, which explicitly returns (separate) information about the caller and its children, may be preferable.
The C standard allows for arbitrary values at the start of the program; subtract the value returned from a call to clock() at the start of the program to get maximum portability.
C標準允許在程序開始設置一個任意值減去"clock()"的返回值 作為結果
以方便移植
The value returned is the CPU time used so far as a clock_t; to get the
number of seconds used, divide by CLOCKS_PER_SEC. If the processor
time used is not available or its value cannot be represented, the
function returns the value (clock_t) -1.
函數的返回值 使用的秒數除以CLOCKS_PER_SEC (32位系統這個數是1000000)
如果time不可用 返回(clock_t) -1
linux里面不會收集子進程的CPU使用時間
但某些其他實現收集子進程CPU使用時間
- 4 回答
- 0 關注
- 2249 瀏覽
添加回答
舉報