C++ timing, milliseconds since last whole second

2020-06-20 05:25发布

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?

10条回答
做个烂人
2楼-- · 2020-06-20 06:15

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
查看更多
甜甜的少女心
3楼-- · 2020-06-20 06:15

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.

查看更多
▲ chillily
4楼-- · 2020-06-20 06:18

Intel's Threading Building Blocks library has a function for this, but TBB is currently only availble on Intel and clones (that is, it's not available on SPARCs, PowerPC, ARM, etc.)

查看更多
女痞
5楼-- · 2020-06-20 06:26

Anything not in the (c)time.h header requires OS-specific methods. I believe all those methods are second resolution.

What OS are you working in?

查看更多
登录 后发表回答