fork download
  1. #include <iostream>
  2. #include <iomanip>
  3.  
  4. #include <random>
  5. #include <chrono>
  6.  
  7. #include <algorithm>
  8. #include <numeric>
  9.  
  10. #include <set>
  11. #include <vector>
  12. #include <cstring>
  13.  
  14.  
  15. std::vector<char> chars(10'000'000);
  16.  
  17.  
  18.  
  19. namespace {
  20. using namespace std::chrono;
  21. struct Timer {
  22. using my_clock = high_resolution_clock;
  23. my_clock::time_point start;
  24. Timer() :start{ my_clock::now() } {}
  25. auto finish() {
  26. return duration_cast<microseconds>(my_clock::now() - start);
  27. }
  28. };
  29.  
  30. }
  31.  
  32. void benchmark_strchr(const std::vector<char>& chars, const char* allowed_chars) {
  33. size_t cnt = 0;
  34. Timer t;
  35. for (auto c : chars) {
  36. if (strchr(allowed_chars, c)) {
  37. cnt++;
  38. }
  39. }
  40. auto d = t.finish();
  41. std::cout << "strchr found " << std::setw(9) << cnt << " in " << std::setw(9) << d.count() << " us" << std::endl;
  42. }
  43.  
  44.  
  45. void benchmark_set(const std::vector<char>& chars, std::set<char> allowed_chars) {
  46. size_t cnt = 0;
  47. Timer t;
  48. for (auto c : chars) {
  49. if (allowed_chars.find(c) != allowed_chars.end()) {
  50. cnt++;
  51. }
  52. }
  53. auto d = t.finish();
  54. std::cout << "set found " << std::setw(9) << cnt << " in " << std::setw(9) << d.count() << " us" << std::endl;
  55. }
  56.  
  57. int main()
  58. {
  59. std::random_device rd;
  60. std::uniform_int_distribution<int> dist('A', 'z');
  61. for (auto& c : chars) {
  62. c = dist(rd);
  63. }
  64.  
  65. benchmark_strchr(chars, "ab");
  66. benchmark_set(chars, { 'a','b'});
  67. benchmark_strchr(chars, "abcdef");
  68. benchmark_set(chars, { 'a','b','c','d','e','f'});
  69. benchmark_strchr(chars, "abcdefghijkl");
  70. benchmark_set(chars, { 'a','b','c','d','e','f','g','h','i','j','k','l' });
  71. benchmark_strchr(chars, "abcdefghijklmnopqrstuvwxyz");
  72. benchmark_set(chars, { 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' });
  73.  
  74. std::vector<char> all_ascii(125);
  75. std::iota(all_ascii.begin(), all_ascii.end(), (char)1);
  76. all_ascii.back() = '\0';
  77. benchmark_strchr(chars, all_ascii.data());
  78. benchmark_set(chars, std::set<char>(all_ascii.begin(),all_ascii.end()));
  79. }
Success #stdin #stdout 2.74s 3472KB
stdin
Standard input is empty
stdout
strchr found    344648 in     47764 us
set    found    344648 in     58948 us
strchr found   1034319 in     76746 us
set    found   1034319 in     75409 us
strchr found   2069248 in    105444 us
set    found   2069248 in     96014 us
strchr found   4483843 in    168902 us
set    found   4483843 in    137364 us
strchr found  10000000 in    458017 us
set    found  10000000 in    301340 us