I am trying to log milliseconds of time that has elapsed over a period of time.
I have a class like this
// class member declarations
class MyClass {
std::chrono::high_resolution_clock::time_point m_start;
std::chrono::system_clock::duration m_elapsed;
};
I have 2 methods in the class. One is called from main that is func1CalledFromMainThread
.
// Class methods
using namespace std::chrono;
void MyClass::func1CalledFromMainThread() {
m_start = std::chrono::high_resolution_clock::now();
}
And another one that is func2CalledFromADifferentThread
is called from a different thread
void MyClass::func2CalledFromADifferentThread() {
// after some time following line of code runs from a different thread
auto end = high_resolution_clock::now();
m_elapsed = duration_cast<milliseconds>(end - m_start);
std::cout << "Elapsed time in milliseconds is " << m_elapsed.count()/1000 << std::endl;
}
The issue is in the cout
logging. I see that I have to divide by 1000
to get milliseconds out of m_elapsed
. Doesn't count
return the count of std::chrono::milliseconds
here? Why should I have to divide by 1000
here? Does count()
return always in microseconds
or am I doing a mistake?
count
returns the number of ticks of the type on which you invoke it. If you wrote this:
duration_cast<milliseconds>(end - m_start).count()
it would correctly give you the number of milliseconds. However, you're not storing the result in std::chrono::milliseconds
, you're storing it in std::chrono::system_clock::duration
(the type of m_elapsed
). Therefore, m_elapsed.count()
returns the number of ticks in std::chrono::system_clock::duration
's frequency, which is probably microseconds on your platform.
In other words, you're immediately undoing the cast to milliseconds
by storing the result in something other than milliseconds
.