Re: [問題] 亂數程式連續執行

看板C_and_CPP作者 (小風)時間14年前 (2010/02/10 15:22), 編輯推噓4(403)
留言7則, 5人參與, 最新討論串3/6 (看更多)
在下提供一個方法, 利用 CPU cycle 當種子, 這樣做可以確保每次取得 的亂數都會不一樣, 因為 CPU cycle 是一個 hardware status, 在系統 上所有的 process 都會讓 CPU cycle 的值增加, 因此在 software level 無法預測它的值, 也不需要利用 sleep 或跑迥圈拖慢執行速度, 但缺點 是利用 assembly 的關係, 若在不同平台上, 要有不同的 implementation, 以下提供 x86 上的做法如下: void my_srand(void) { long long cpu_cycle; asm volatile(".byte 15;.byte 49" : "=A" (cpu_cycle)); srand((unsigned int)cpu_cycle); } 只要利用上述這個 function 取代原有的 srand() 就可以了, 大致上 用法如下: int main() { int r_num; my_srand(); r_num = rand(); ....... } ※ 引述《justinC (無)》之銘言: : 遇到的問題: (題意請描述清楚) : 我的亂數程式在連續執行時, 由於時間間隔很短, : srand() 傳入的參數一樣,而造成兩次得到的亂數值相同, : 有人知道該如何將他打亂嗎? : update: 想到一個解法...加上 process pid : 程式跑出來的錯誤結果: : >./a.out && ./a.out : i=1 : i=2 : i=6 : i=3 : i=2 : --- : i=1 : i=2 : i=6 : i=3 : i=2 : --- : 開發平台: (例: VC++ or gcc/g++ or Dev-C++, Windows or Linux) : Freebsd : 有問題的code: (請善用置底文標色功能) : #include <stdio.h> : #include <stdlib.h> : #include <time.h> : void f() : { : int iSecret; : iSecret = rand() % 10 + 1; : printf("i=%d\n",iSecret); : } : int main () : { : int iSecret;[A : srand (time(NULL) ); : int k=0; : for(k=0;k<5;k++){ : f(); : } : printf("---\n"); : return 0; : } : 補充說明: -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 60.249.207.134

02/10 15:28, , 1F
cool....:)
02/10 15:28, 1F

02/10 15:39, , 2F
good
02/10 15:39, 2F

02/10 15:50, , 3F
"=A" 這是 gcc 的寫法吧...VC 可能要換種寫法
02/10 15:50, 3F

02/10 15:50, , 4F
不過不可否認 用cpu cycle是個好主意
02/10 15:50, 4F

02/10 16:32, , 5F
推 有沒有辦法不用assembly就做到相同的效果?
02/10 16:32, 5F

02/10 17:00, , 6F
Sorry,忘了說,這是gcc inline assembly,而且因為c不允許直
02/10 17:00, 6F

02/10 17:01, , 7F
接讀cpu register,所以必須用assembly
02/10 17:01, 7F
文章代碼(AID): #1BSbwxcp (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1BSbwxcp (C_and_CPP)