I do not understand the following behaviour
unsigned long begin_time = \
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count();
//some code here
std::cout << "time diff with arithmetic in cout: " << \
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count() - begin_time << std::endl;
unsigned long time_diff = \
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count() - begin_time;
std::cout << "time_diff: " << time_diff << std::endl;
Output:
time diff with arithmetic in cout: <very large number (definitely not milliseconds)>
time_diff: <smaller number (definitely milliseconds)>
Why does the duration_cast
not work when I do arithmetic within the cout? I have used unsigned int
and int
for the time_diff
variable, but I always get good output when I first do the arithmetic within the variable initialization or assignment.
NOTE
I am using Visual Studio 2013 (Community edition)
You are probably overflowing unsigned long
(sizeof is 4):
unsigned long begin_time = \
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count();
Recommended:
using namespace std::chrono;
auto begin_time = steady_clock::now();
//some code here
std::cout << "time diff with arithmetic in cout: " <<
duration_cast<milliseconds>(steady_clock::now() - begin_time).count() << std::endl;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With