毫秒级随机数

· · 个人记录

众所周知,重复打开相同的可执行文件,想要输出的数不同,往往需要以时间作为随机种子。

如:

#include<bits/stdc++.h>
using namespace std;
signed main(){
    srand(time(0));
    int a = rand();
    printf("%d\n",a);
    return 0;
}

但是,以这种方式,在代码上使用 \text{While} 下每毫秒随机一个:

但在使用重复运行 \text{exe} ,在每 1 秒内重复运行这个程序,输出的随机数都是相同的。

那么,想要打破这个 “1 秒限制”,就需要用到 timeb。

#include<bits/stdc++.h>
using namespace std;
signed main(){
    struct _timeb T;
    _ftime(&T);
    srand(T.millitm);
    int a = rand();
    printf("%d\n", a);
    return 0;
}

这样,在 1 秒内反复执行程序:

可以看到每次执行程序输出的随机数都不同。

这样,就实现 “生成毫秒级别随机数” 了。