fork(14) download
  1. #include <cstdio>
  2. #include<iostream>
  3. #include <sstream>
  4. #include <chrono>
  5.  
  6. std::chrono::time_point<std::chrono::steady_clock> hClock()
  7. {
  8. return std::chrono::steady_clock::now();
  9. }
  10.  
  11. std::uint32_t TimeDuration(std::chrono::time_point<std::chrono::steady_clock> Time)
  12. {
  13. return std::chrono::duration_cast<std::chrono::nanoseconds>(hClock() - Time).count();
  14. }
  15.  
  16.  
  17. void Benchmark(const char* Name, std::string &str, void(*func)(std::string &str))
  18. {
  19. auto time = hClock();
  20. for (int i = 0; i < 100; ++i)
  21. {
  22. func(str);
  23. str.clear();
  24. }
  25. std::cout<<Name<<" took: "<<TimeDuration(time) / 100<<" nano-seconds.\n";
  26. }
  27.  
  28. void unlocked_bench(std::string &str)
  29. {
  30. char c = '0';
  31. while((c = getchar_unlocked()) && (c != -1 && c != '\n' && c != '\r'))
  32. {
  33. str += c;
  34. }
  35. }
  36.  
  37. void getchar_bench(std::string &str)
  38. {
  39. char c = '0';
  40. while((c = getchar()) && (c != -1 && c != '\n' && c != '\r'))
  41. {
  42. str += c;
  43. }
  44. }
  45.  
  46. void getline_bench(std::string &str)
  47. {
  48. std::cin.getline(&str[0], str.size());
  49. }
  50.  
  51. void scanf_bench(std::string &str)
  52. {
  53. scanf("%[^\n]100s", &str[0]);
  54. }
  55.  
  56. void fgets_bench(std::string &str)
  57. {
  58. fgets(&str[0], str.size(), stdin);
  59. }
  60.  
  61. void cinread_bench(std::string &str)
  62. {
  63. std::cin.read(&str[0], str.size());
  64. }
  65.  
  66. int main()
  67. {
  68. std::string str;
  69. str.reserve(100);
  70.  
  71. Benchmark("getchar_unlocked", str, unlocked_bench);
  72. Benchmark("getchar", str, getchar_bench);
  73. Benchmark("getline", str, getline_bench);
  74. Benchmark("scanf", str, scanf_bench);
  75. Benchmark("fgets", str, fgets_bench);
  76. Benchmark("cinread", str, cinread_bench);
  77.  
  78. return 0;
  79. }
Success #stdin #stdout 0s 3480KB
stdin
Hello There
Hello There
Hello There
Hello There
Hello There
Hello There
Hello There
Hello There
Hello There
Hello There
Hello There
Hello There
Hello There
Hello There
Hello There
Hello There
Hello There
Hello There
stdout
getchar_unlocked took: 436 nano-seconds.
getchar took: 330 nano-seconds.
getline took: 619 nano-seconds.
scanf took: 522 nano-seconds.
fgets took: 44 nano-seconds.
cinread took: 67 nano-seconds.