Stefan B Stefan B - 3 years ago 199
C++ Question

c++ std chrono overflow

I am trying to implement a stopwatch for debugging as follows:

#include <chrono>

namespace sbstd
class timer
bool m_running = false;
std::chrono::time_point<std::chrono::system_clock> m_temp;
std::chrono::nanoseconds m_time;
void start()
if (m_running) { throw std::exception("timer already running"); }
m_temp = std::chrono::system_clock::now();
m_running = true;

void stop()
if (!m_running) { throw std::exception("timer not started"); }
m_time += std::chrono::system_clock::now() - m_temp;
m_running = false;

long long get_ms() const
return std::chrono::duration_cast<std::chrono::milliseconds>(m_time).count();

In the main method I have the following:

sbstd::timer t1;
cout << t1.get_ms();

Instead of 5000 I get a negative int.

What is wrong?

Answer Source

m_time is not initialised so its value is indeterminate - its just some garbage value. You probably want to initialise it to 0 - use std::chrono::nanoseconds::zero(). Here it is in action.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download