Why isn't the speed of AMD 5600 hardware random number generator steady in my C++ code?

163 Views Asked by At

I was testing the speed of AMD 5600 h/w random number generator (rdrand) in C++ and found the speed isn't steady. Is this normal or am I doing something wrong ?

Here is the used code:

#include <iostream>
#include <chrono>
#include <cstdint>

int main()
{
    uint64_t random_num;
    int iter = 5'000'000;

    auto start = std::chrono::high_resolution_clock::now();

    for (int i = 0; i < iter; i++) {
        __asm__ volatile("rdrand %0" : "=r"(random_num));
    }

    auto end = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();

    std::cout << iter << " iterations in " << duration << " ms" << std::endl;


    return 0;
}

Here are the results:

mika@pc3 ~/t $ g++ -O2 rdrand.cpp -o rdrand
mika@pc3 ~/t $ ./rdrand
5000000 iterations in 79 ms
mika@pc3 ~/t $ ./rdrand
5000000 iterations in 79 ms
mika@pc3 ~/t $ ./rdrand
5000000 iterations in 79 ms
mika@pc3 ~/t $ ./rdrand
5000000 iterations in 4458 ms
mika@pc3 ~/t $ ./rdrand
5000000 iterations in 4251 ms
mika@pc3 ~/t $ ./rdrand
5000000 iterations in 4312 ms
mika@pc3 ~/t $ ./rdrand
5000000 iterations in 4209 ms
mika@pc3 ~/t $ ./rdrand
5000000 iterations in 4571 ms
0

There are 0 best solutions below