Time difference in C++

2019-01-10 14:31发布

Does anyone know how to calculate time difference in C++ in milliseconds? I used difftime but it doesn't have enough precision for what I'm trying to measure.

标签: c++ time
8条回答
成全新的幸福
2楼-- · 2019-01-10 15:17

If you're looking to do benchmarking, you might want to see some of the other threads here on SO which discuss the topic.

Also, be sure you understand the difference between accuracy and precision.

查看更多
不美不萌又怎样
3楼-- · 2019-01-10 15:21

You have to use one of the more specific time structures, either timeval (microsecond-resolution) or timespec (nanosecond-resolution), but you can do it manually fairly easily:

#include <time.h>

int diff_ms(timeval t1, timeval t2)
{
    return (((t1.tv_sec - t2.tv_sec) * 1000000) + 
            (t1.tv_usec - t2.tv_usec))/1000;
}

This obviously has some problems with integer overflow if the difference in times is really large (or if you have 16-bit ints), but that's probably not a common case.

查看更多
登录 后发表回答