C++的时差

Ale*_*ejo 31 c++ time

有谁知道如何用毫秒计算C++的时差?我曾经使用difftime但它没有足够的精度来衡量我正在测量的东西.

How*_*ant 73

我知道这是一个老问题,但有一个更新的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
Run Code Online (Sandbox Code Playgroud)

更多信息可以在这里找到:

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

现在还有一个推动实施<chrono>.


Tyl*_*nry 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;
}
Run Code Online (Sandbox Code Playgroud)

如果时间差异非常大(或者如果你有16位整数),这显然存在整数溢出的一些问题,但这可能不是常见的情况.

  • 您可能希望在除以1000之前添加+500 usec,以便999usec向上舍入为1毫秒而不是0毫秒. (3认同)
  • 不,我的意思是*1000000.它在我们中进行计算,然后在最后转换为ms.不过,+ 500的建议很好. (3认同)

Nun*_*uno 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 );
}
Run Code Online (Sandbox Code Playgroud)


Bil*_*ard 5

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

#include <time.h>

int clo = clock();
//do stuff
cout << (clock() - clo) << endl;
Run Code Online (Sandbox Code Playgroud)

并看看你的结果如何.