fork(2) download
  1. #include <time.h>
  2.  
  3. #include <atomic>
  4. #include <mutex>
  5.  
  6. static std::atomic<bool> single_threaded(true);
  7.  
  8. int main(int argc, char *argv[])
  9. {
  10. (void)argv;
  11. if (argc == 100001) { single_threaded = !single_threaded; /* to prevent compiler optimization later */ }
  12. int n = argc == 100000 ? -1 : 10000000;
  13. {
  14. std::mutex mutex;
  15. clock_t const begin = clock();
  16. unsigned int total = 0;
  17. for (int i = 0; i < n; ++i)
  18. {
  19. if (single_threaded)
  20. {
  21. total = ((total << 1) ^ i) + ((total >> 1) & i);
  22. }
  23. else
  24. {
  25. std::lock_guard<std::mutex> lock(mutex);
  26. total = ((total << 1) ^ i) + ((total >> 1) & i);
  27. }
  28. }
  29. clock_t const end = clock();
  30. printf("Conditional: %u ms, total = %u\n", (unsigned int)((end - begin) * 1000U / CLOCKS_PER_SEC), total);
  31. }
  32. {
  33. std::mutex mutex;
  34. clock_t const begin = clock();
  35. unsigned int total = 0;
  36. for (int i = 0; i < n; ++i)
  37. {
  38. std::lock_guard<std::mutex> lock(mutex);
  39. total = ((total << 1) ^ i) + ((total >> 1) & i);
  40. }
  41. clock_t const end = clock();
  42. printf("Unconditional: %u ms, total = %u\n", (unsigned int)((end - begin) * 1000U / CLOCKS_PER_SEC), total);
  43. }
  44. }
Success #stdin #stdout 0.34s 3456KB
stdin
Standard input is empty
stdout
Conditional: 27 ms, total = 3684292139
Unconditional: 311 ms, total = 3684292139