I'm working on a C++ application that needs detailed timing information, down to the millisecond level.
We intend to gather the time to second accuracy using the standard time()
function in <ctime>
. We would like to additionally gather the milliseconds elapsed since the last second given by time()
.
Does anyone know a convenient method for obtaining this information?
Boost.DateTime has millisecond and nanosecond representations IF the underlying platform supports them. While it is using platform specific code, it is keeping those details out of your code.
If that is a big deal, they do have another way of doing platform independent subsecond resolution. This page a couple of paragraphs down talks about how to do it.
(From the Page)
For example, let's suppose we want to construct using a count that represents tenths of a second. That is, each tick is 0.1 second.
int number_of_tenths = 5;
//create a resolution independent count -- divide by 10 since there are
//10 tenths in a second.
int count = number_of_tenths*(time_duration::ticks_per_second()/10);
time_duration td(1,2,3,count); //01:02:03.5 //no matter the resolution settings
There is not a portable solution to this problem, since ANSI C does not define a standard millisecond-accurate time function. If you're using Windows, you can use GetTickCount(), timeGetTime(), or QueryPerformanceCounter()/QueryPerformanceFrequency(). Keep in mind that these have different accuracies and different runtime costs.
There are other similar functions in other operating systems; I'm not sure what they are off the top of my head.
GetTickCount in Windows gettimeofday in *nix QueryPerformanceCounter in Windows for better resolution (though GetTickCount should do it)
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