Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ timing, milliseconds since last whole second

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?

like image 468
user20716 Avatar asked Sep 22 '08 20:09

user20716


3 Answers

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
like image 167
Justin Rudd Avatar answered Sep 23 '22 05:09

Justin Rudd


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.

like image 28
Adam Rosenfield Avatar answered Sep 22 '22 05:09

Adam Rosenfield


GetTickCount in Windows gettimeofday in *nix QueryPerformanceCounter in Windows for better resolution (though GetTickCount should do it)

like image 45
INS Avatar answered Sep 20 '22 05:09

INS