有谁知道如何在 C++ 中以毫秒为单位计算时间差?我使用了 difftime
但它没有足够的精度我正在尝试测量什么.
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.
您必须使用一种更具体的时间结构,timeval(微秒分辨率)或 timespec(纳秒分辨率),但您可以手动进行相当容易:
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;
}
如果时间差异非常大(或者如果您有 16 位整数),这显然存在整数溢出问题,但这可能不是常见情况.
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.
这篇关于C++中的时差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!