fork(1) download
  1. #include <string>
  2. #include <chrono>
  3. #include <iostream>
  4. #include <system_error>
  5. #include <cerrno>
  6. #include <signal.h>
  7.  
  8. constexpr unsigned int iter_count = 1000000;
  9.  
  10. template<typename F>
  11. void bench(std::string name,
  12. F func,
  13. unsigned int iterations = iter_count){
  14. using namespace std::chrono;
  15.  
  16. std::cout<<"Benchmarking \""
  17. <<name<<"\" with "<<iterations<<" iterations"
  18. <<std::endl;
  19.  
  20. auto begin = steady_clock::now();
  21.  
  22. for(unsigned int i = 0; i != iterations; i++)
  23. func();
  24.  
  25. auto end = steady_clock::now();
  26. auto elapsed = duration_cast<milliseconds>(end - begin).count();
  27.  
  28. std::cout<<elapsed<<" miliseconds to run \""<<name<<"\""<<std::endl;
  29. }
  30.  
  31. int failing_func(){
  32. sigset_t sig;
  33. return sigprocmask(-1, &sig, nullptr);
  34. }
  35.  
  36. int success_func(){
  37. return sigprocmask(0, nullptr, nullptr);
  38. }
  39.  
  40. void with_exception_oftenfail(){
  41. int res = failing_func();
  42. if(res == -1) throw std::system_error(errno, std::system_category());
  43. }
  44.  
  45. int with_error_code_oftenfail(){
  46. return failing_func();
  47. }
  48.  
  49. void with_exception_rarefail(){
  50. int res = success_func();
  51. if(res == -1) throw std::system_error(errno, std::system_category());
  52. }
  53.  
  54. int with_error_code_rarefail(){
  55. return success_func();
  56. }
  57.  
  58. int main(){
  59. unsigned int black_hole = 0;
  60. bench("Exceptions (often error)", [&black_hole](){
  61. try{
  62. with_exception_oftenfail();
  63. } catch(std::exception& e){
  64. black_hole++;
  65. }
  66. });
  67.  
  68. bench("Error codes (often error)", [&black_hole](){
  69. int res = with_error_code_oftenfail();
  70. if(res == -1) black_hole--;
  71. });
  72.  
  73. bench("Exceptions (rare error)", [&black_hole](){
  74. try{
  75. with_exception_rarefail();
  76. } catch(std::exception& e){
  77. black_hole++;
  78. }
  79. });
  80.  
  81. bench("Error codes (rare error)", [&black_hole](){
  82. int res = with_error_code_rarefail();
  83. if(res == -1) black_hole--;
  84. });
  85.  
  86. //To prevent loop optimize-out
  87. std::cout<<"Blackhole is:"<<black_hole<<std::endl;
  88. }
  89.  
Success #stdin #stdout 2.41s 16064KB
stdin
Standard input is empty
stdout
Benchmarking "Exceptions (often error)" with 1000000 iterations
2289 miliseconds to run "Exceptions (often error)"
Benchmarking "Error codes (often error)" with 1000000 iterations
60 miliseconds to run "Error codes (often error)"
Benchmarking "Exceptions (rare error)" with 1000000 iterations
37 miliseconds to run "Exceptions (rare error)"
Benchmarking "Error codes (rare error)" with 1000000 iterations
35 miliseconds to run "Error codes (rare error)"
Blackhole is:0