#include <string> #include <iostream> #include <vector> #include <chrono> static const char CHARS[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; static const int BENCHMARK_SIZE = 10000000; static const int MAX_STRING_LENGTH = 50; using time_point = std::chrono::high_resolution_clock::time_point; void benchmark(std::vector<std::string> &list) { std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now(); // force a copy of each string in the loop iteration for (const auto s : list) { static_cast<void>(s); } std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now(); const auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count(); std::cerr << list[0].length() << ',' << duration << '\n'; } void generate_random_string(std::string &str, const int length) { static float pi_number = 10 / 7; for (int i = 0; i < length; ++i) { str[i] = CHARS[(int)pi_number]; } pi_number = (pi_number - int(pi_number)) * 10; // gives values of pi on and on. } int main() { std::cerr << "length,time\n"; std::vector<std::string> list; list.resize(BENCHMARK_SIZE); for (int length = 1; length <= MAX_STRING_LENGTH; length++) { for (int i = 0; i < BENCHMARK_SIZE; i++) { list[i].resize(length); generate_random_string(list[i], length); } benchmark(list); } return 0; }
Standard input is empty
Standard output is empty
length,time 1,36 2,55 3,56 4,53 5,54 6,55 7,58 8,50 9,48 10,49 11,48 12,51 13,49 14,51 15,49 16,197 17,203 18,200 19,200 20,203