mardi 11 août 2020

What is the most efficient way to generate random strings in C++?

I need to generate random strings efficiently. In the following, you will see my first try. I compiled the code with gcc and -O3 optimization level. It takes 18.5 seconds to generate 10^7 random strings of length 64:

#include <iostream>
#include <random>
#include <algorithm>

std::string chars {"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()`~-_=+[{]{|;:'\",<.>/?"};
std::random_device rd;
std::mt19937 generator(rd());
  
std::string rand_str (int length) {
  std::string output (chars);
  std::shuffle(output.begin(), output.end(), generator);
  return output.substr(0, length);
}

int main() {
  int i = 0;
  std::string rand_bytes;
  for (long i=0; i<10000000; ++i)
      rand_bytes = rand_str (64);
}

I checked std::sample in c++17 and it is not faster than above method.

Question

  • Are there are more efficient ways to do this in modern C++?

I appreciate any suggestions to improve the code.




Aucun commentaire:

Enregistrer un commentaire