Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <chrono>
- #include <iomanip>
- #include <iostream>
- // Illustrates a bug in the clang compiler.
- // When overflow occurs in std::chrono computations, the resultant values don't
- // compare as they should.
- //
- // Failure case: optimized at O2 or O3
- // clang++ -std=c++11 -O2 duration_compare_fail.cc
- // ./a.out
- //
- // Success case: optimized at O0 or O1
- // clang++ -std=c++11 -O1 duration_compare_fail.cc
- // ./a.out
- //
- // See documentation below for expected outcome.
- using std::chrono::duration;
- using std::chrono::steady_clock;
- using std::chrono::time_point;
- using std::ostream;
- // Print out a duration as number of ticks * ratio.
- template <typename rep, typename per>
- ostream& operator<<(ostream& out, const duration<rep, per>& duration) {
- out << duration.count() << " * " << per::num << " / " << per::den;
- return out;
- }
- // Prints a time period by printing its underlying duration from epoch.
- template <typename c, typename d>
- ostream& operator<<(ostream& out, const time_point<c, d>& time) {
- out << time.time_since_epoch();
- return out;
- }
- // Simply show a variable/expression and its value.
- #define PRINT(v) std::cout << #v << ": " << (v) << "\n";
- int main() {
- std::cout << std::setprecision(16);
- std::cout << "Math directly with longs works\n";
- steady_clock::duration::rep a = 9223372036854775807L;
- steady_clock::duration::rep b = 2098958597616352L;
- steady_clock::duration::rep c;
- PRINT(a);
- PRINT(b);
- PRINT(c = a + b);
- // This will print true; c is a result of overflow and is negative.
- PRINT(c < b);
- std::cout << "\nComparable math with durations fails\n";
- const steady_clock::duration delay = steady_clock::duration::max();
- const time_point<steady_clock> now = steady_clock::now();
- const time_point<steady_clock> wrap = now + delay;
- PRINT(delay);
- PRINT(now);
- PRINT(wrap);
- // This will only print true with low optimization. However, the count for
- // each time point's
- PRINT(wrap < now);
- PRINT(wrap.time_since_epoch() < now.time_since_epoch());
- PRINT(wrap.time_since_epoch().count() < now.time_since_epoch().count());
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement