Commit 946a4524 authored by Stefan Westerfeld's avatar Stefan Westerfeld

Optimize performance of Random generator.

Signed-off-by: Stefan Westerfeld's avatarStefan Westerfeld <stefan@space.twc.de>
parent 1fad8725
...@@ -3,6 +3,8 @@ ...@@ -3,6 +3,8 @@
#include <regex> #include <regex>
#include <assert.h>
using std::string; using std::string;
using std::vector; using std::vector;
using std::regex; using std::regex;
...@@ -103,16 +105,25 @@ Random::get_start_counter (uint64_t seed, Stream stream) ...@@ -103,16 +105,25 @@ Random::get_start_counter (uint64_t seed, Stream stream)
uint64_t uint64_t
Random::operator()() Random::operator()()
{ {
const size_t block_size = 8; if (buffer_pos == buffer.size())
unsigned char zeros[block_size] = { 0, }; {
unsigned char cipher_text[block_size]; const size_t block_size = 256;
unsigned char zeros[block_size] = { 0, };
unsigned char cipher_text[block_size];
gcry_error_t gcry_ret = gcry_cipher_encrypt (aes_ctr_cipher, cipher_text, block_size, zeros, block_size); gcry_error_t gcry_ret = gcry_cipher_encrypt (aes_ctr_cipher, cipher_text, block_size, zeros, block_size);
die_on_error ("gcry_cipher_encrypt", gcry_ret); die_on_error ("gcry_cipher_encrypt", gcry_ret);
// print ("AES OUT", {cipher_text, cipher_text + block_size}); // print ("AES OUT", {cipher_text, cipher_text + block_size});
return uint64_from_buffer (&cipher_text[0]); buffer.clear();
for (size_t i = 0; i < block_size; i += 8)
buffer.push_back (uint64_from_buffer (cipher_text + i));
buffer_pos = 0;
}
assert (buffer_pos < buffer.size());
return buffer[buffer_pos++];
} }
void void
......
...@@ -17,6 +17,9 @@ public: ...@@ -17,6 +17,9 @@ public:
}; };
private: private:
gcry_cipher_hd_t aes_ctr_cipher; gcry_cipher_hd_t aes_ctr_cipher;
std::vector<uint64_t> buffer;
size_t buffer_pos = 0;
std::vector<unsigned char> get_start_counter (uint64_t seed, Stream stream); std::vector<unsigned char> get_start_counter (uint64_t seed, Stream stream);
void die_on_error (const char *func, gcry_error_t error); void die_on_error (const char *func, gcry_error_t error);
......
...@@ -27,7 +27,7 @@ main (int argc, char **argv) ...@@ -27,7 +27,7 @@ main (int argc, char **argv)
uint64_t s = 0; uint64_t s = 0;
double t_start = gettime(); double t_start = gettime();
size_t runs = 1000000; size_t runs = 25000000;
for (size_t i = 0; i < runs; i++) for (size_t i = 0; i < runs; i++)
{ {
s += rng(); s += rng();
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment