C ++的时差

时间:2008-11-21 01:59:34

标签: c++ time

有谁知道如何用毫秒来计算C ++中的时差? 我使用difftime,但它没有足够的精度来测量我想要的东西。

8 个答案:

答案 0 :(得分:71)

我知道这是一个老问题,但是有一个更新的C ++ 0x答案。有一个名为<chrono>的新标头,其中包含现代时间实用程序。使用示例:

#include <iostream>
#include <thread>
#include <chrono>

int main()
{
    typedef std::chrono::high_resolution_clock Clock;
    typedef std::chrono::milliseconds milliseconds;
    Clock::time_point t0 = Clock::now();
    std::this_thread::sleep_for(milliseconds(50));
    Clock::time_point t1 = Clock::now();
    milliseconds ms = std::chrono::duration_cast<milliseconds>(t1 - t0);
    std::cout << ms.count() << "ms\n";
}

50ms

可在此处找到更多信息:

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2661.htm

现在还有<chrono>的推动实施。

答案 1 :(得分:19)

您必须使用其中一个更具体的时间结构,timeval(微秒分辨率)或timespec(纳秒分辨率),但您可以相当轻松地手动完成:

#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位整数),这显然存在整数溢出的一些问题,但这可能不是常见的情况。

答案 2 :(得分:7)

如果你使用win32 FILETIME是最准确的: 包含一个64位值,表示自1601年1月1日(UTC)以来100纳秒间隔的数量。

因此,如果您想以毫秒为单位计算两次之间的差异,请执行以下操作:

UINT64 getTime()
{
    SYSTEMTIME st;
    GetSystemTime(&st);

    FILETIME ft;
    SystemTimeToFileTime(&st, &ft);  // converts to file time format
    ULARGE_INTEGER ui;
    ui.LowPart=ft.dwLowDateTime;
    ui.HighPart=ft.dwHighDateTime;

    return ui.QuadPart;
}

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
    //! Start counting time
    UINT64   start, finish;

    start=getTime();

    //do something...

    //! Stop counting elapsed time
    finish = getTime();

    //now you can calculate the difference any way that you want
    //in seconds:
    _tprintf(_T("Time elapsed executing this code: %.03f seconds."), (((float)(finish-start))/((float)10000))/1000 );
    //or in miliseconds
    _tprintf(_T("Time elapsed executing this code: %I64d seconds."), (finish-start)/10000 );
}

答案 3 :(得分:5)

时钟功能为您提供毫秒计时器,但它不是最好的。它的真正分辨率取决于您的系统。你可以尝试

#include <time.h>

int clo = clock();
//do stuff
cout << (clock() - clo) << endl;

并查看结果如何。

答案 4 :(得分:2)

您可以使用gettimeofday来获取自纪元以来的微秒数。 gettimeofday()返回的值的秒段与time()返回的值相同,可以强制转换为time_t并在difftime中使用。毫秒是1000微秒。

使用difftime后,自己计算微秒字段的差异。

答案 5 :(得分:2)

您可以从Boost.Date_Time中获得微秒和纳秒的精度。

答案 6 :(得分:1)

如果您希望进行基准测试,您可能希望在SO上看到一些讨论该主题的other threads

另外,请务必了解准确度和精确度之间的差异。

答案 7 :(得分:0)

我认为你必须使用特定于平台的东西。希望那没关系? 例如。在Windows上,查看QueryPerformanceCounter(),这将为您提供更多帮助 好于毫秒。