本文对比C++中std::mt19937和硬件随机数效率。注意硬件随机数指令_rdrand32_step等属于AVX指令集。文档中说明_rdrand32_step可能会失败,失败时返回0,经过几次测试没有发现失败的情况。所以如果程序要求不严可以不管返回值。对比的结果是硬件随机数更慢。所以一般硬件随机数只产生一次用作软件随机数的种子。C++标准库中已实现了硬件随机数类,名为std::random_device。下述代码基于VS2017、OpenCV430和Qt5.9。CPU型号是Intel Core i5-7400。下面是对比所用代码:
void main() { int64 t1, t2; uint sum = 0; std::mt19937 mt; t1 = getTickCount(); for (int i = 0; i < 10000000; i++) { sum += mt(); } t2 = getTickCount(); qDebug() << u8"software(ms):" << (t2 - t1) / getTickFrequency() * 1000; qDebug() << sum; sum = 0; t1 = getTickCount(); for (int i = 0; i < 10000000; i++) { uint x; _rdrand32_step(&x); sum += x; } t2 = getTickCount(); qDebug() << u8"hardware(ms):" << (t2 - t1) / getTickFrequency() * 1000; qDebug() << sum; }
运行输出为:
software(ms): 45.4946 544921821 hardware(ms): 1272.13 1714828820
标签:std,rdrand32,软硬件,t2,硬件,随机数,对比 From: https://www.cnblogs.com/mengxiangdu/p/17376321.html