Advertisement
Guest User

Untitled

a guest
Mar 20th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. #include <chrono>
  2. #include <iomanip>
  3. #include <iostream>
  4.  
  5. // Illustrates a bug in the clang compiler.
  6. // When overflow occurs in std::chrono computations, the resultant values don't
  7. // compare as they should.
  8. //
  9. // Failure case: optimized at O2 or O3
  10. // clang++ -std=c++11 -O2 duration_compare_fail.cc
  11. // ./a.out
  12. //
  13. // Success case: optimized at O0 or O1
  14. // clang++ -std=c++11 -O1 duration_compare_fail.cc
  15. // ./a.out
  16. //
  17. // See documentation below for expected outcome.
  18.  
  19. using std::chrono::duration;
  20. using std::chrono::steady_clock;
  21. using std::chrono::time_point;
  22. using std::ostream;
  23.  
  24. // Print out a duration as number of ticks * ratio.
  25. template <typename rep, typename per>
  26. ostream& operator<<(ostream& out, const duration<rep, per>& duration) {
  27. out << duration.count() << " * " << per::num << " / " << per::den;
  28. return out;
  29. }
  30.  
  31. // Prints a time period by printing its underlying duration from epoch.
  32. template <typename c, typename d>
  33. ostream& operator<<(ostream& out, const time_point<c, d>& time) {
  34. out << time.time_since_epoch();
  35. return out;
  36. }
  37.  
  38. // Simply show a variable/expression and its value.
  39. #define PRINT(v) std::cout << #v << ": " << (v) << "\n";
  40.  
  41. int main() {
  42. std::cout << std::setprecision(16);
  43.  
  44. std::cout << "Math directly with longs works\n";
  45. steady_clock::duration::rep a = 9223372036854775807L;
  46. steady_clock::duration::rep b = 2098958597616352L;
  47. steady_clock::duration::rep c;
  48. PRINT(a);
  49. PRINT(b);
  50. PRINT(c = a + b);
  51. // This will print true; c is a result of overflow and is negative.
  52. PRINT(c < b);
  53.  
  54. std::cout << "\nComparable math with durations fails\n";
  55. const steady_clock::duration delay = steady_clock::duration::max();
  56. const time_point<steady_clock> now = steady_clock::now();
  57. const time_point<steady_clock> wrap = now + delay;
  58. PRINT(delay);
  59. PRINT(now);
  60. PRINT(wrap);
  61. // This will only print true with low optimization. However, the count for
  62. // each time point's
  63. PRINT(wrap < now);
  64. PRINT(wrap.time_since_epoch() < now.time_since_epoch());
  65. PRINT(wrap.time_since_epoch().count() < now.time_since_epoch().count());
  66.  
  67. return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement