Reputation: 2534
I want to write a program to generate really random number using /dev/random
on linux, but later I find the running time of it is quite unacceptable occasionally. C version of it run fast consistently.
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc,char*argv[])
{
ifstream random("/dev/random", ios_base::in);
int t;
random.read(reinterpret_cast<char*>(&t), sizeof(t));
cout << t << endl;
random.close();
return 0;
}
The time statistic of running time
$: time ./random
-1040810404
real 0m0.004s
user 0m0.000s
sys 0m0.000s
$: time ./random
-1298913761
real 0m4.119s
user 0m0.000s
sys 0m0.000s
Upvotes: 5
Views: 1083
Reputation: 14619
You have likely drained the entropy pool. Creating (ok harvesting) entropy is based on device drivers which sample qualities of the physical world which are mostly unpredictable. But if those devices are not very active or if the entropy-producing algorithm stalls, your reads from /dev/random
will too.
Can you use /dev/urandom
? If not, you should look into ways that you can produce more entropy in a more deterministic fashion.
Here are some suggestions from an article regarding a similar problem:
Upvotes: 7