I made a simple Timer class using std::chrono
#include <chrono>
#include <iostream>
#include <thread>
class Timer
{
std::chrono::steady_clock::time_point last;
std::chrono::steady_clock::duration duration;
bool started{};
public:
Timer(bool start = false)
{
if (start)
{
last = std::chrono::steady_clock::now();
started = true;
std::cout<<"started\n";
}
}
void pause()
{
if (started)
{
std::cout<<"paused\n";
duration += (std::chrono::steady_clock::now() - last);
started = false;
}
}
friend std::ostream& operator<<(std::ostream& os, Timer const& t);
~Timer()
{
pause();
std::cout << *this;
}
};
int main()
{
std::cerr << sizeof(size_t) << '\n'; //for indicating 32 or 64 bit
Timer t{true};
std::this_thread::sleep_for(std::chrono::seconds{ 1 });
}
std::ostream& operator<<(std::ostream& os, Timer const& t)
{
os << std::chrono::duration_cast<std::chrono::microseconds>(t.duration).count() << " ms.\n";
return os;
}
When using -m32
flag to compile 32 bit in GCC, it gives ridiculous result:
link
4
started
paused
577755959817856 ms.
But when compiling to 64 bit, the result seems normal: link
8
started
paused
1004260 ms.
EDIT: Yes ms
is a little bit misleading here, should be µs
, but I am lazy to find µ
I think you just have UB on this line,
duration += (std::chrono::steady_clock::now() - last);
because duration
is not initalized.
If you initialize the duration
member
std::chrono::steady_clock::duration duration{};
everything works fine.