本文介绍了C ++中的时差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道如何计算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位int),但这可能不是一个常见的情况。

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 ++中的时差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 05:49