如果在很短的时间内连接获取随机数,会发现获取的随机数是同一个,下面例子可以实现短时间内快速获取不一样的随机数:
#include <windows.h>
#include <iostream>
using namespace std;
//#define USE_QUICK_RAND
DWORD WINAPI thread(PVOID pBuf)
{
LARGE_INTEGER li;
QueryPerformanceCounter(&li);
srand(li.QuadPart);
cout<<"random number: "<<rand();
return 0;
}
void main()
{
for (int i = 0; i < 10; i++)
{
#ifdef USE_QUICK_RAND
LARGE_INTEGER li;
QueryPerformanceCounter(&li);
srand(li.QuadPart);
#else
srand(GetTickCount());
#endif
cout<<"random number: "<<rand()<<endl;
}
}