C++中的时差

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/307596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:30:05  来源:igfitidea点击:

Time difference in C++

c++time

提问by Alejo

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

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

采纳答案by Tyler McHenry

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:

您必须使用更具体的时间结构之一,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;
}

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.

如果时间差异非常大(或者如果您有 16 位整数),这显然会出现整数溢出问题,但这可能不是常见情况。

回答by Howard Hinnant

I know this is an old question, but there's an updated answer for C++0x. There is a new header called <chrono>which contains modern time utilities. Example use:

我知道这是一个老问题,但是 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

More information can be found here:

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

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

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

There is also now a boost implementation of <chrono>.

现在还有一个 boost 实现<chrono>

回答by Nuno

if you are using win32 FILETIME is the most accurate that you can get: Contains a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC).

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

So if you want to calculate the difference between two times in milliseconds you do the following:

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

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 );
}

回答by Bill the Lizard

The clock function gives you a millisecond timer, but it's not the greatest. Its real resolution is going to depend on your system. You can try

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

#include <time.h>

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

and see how your results are.

看看你的结果如何。

回答by Ferruccio

You can get micro and nanosecond precision out of Boost.Date_Time.

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

回答by SoapBox

You can use gettimeofdayto get the number of microseconds since epoch. The seconds segment of the value returned by gettimeofday() is the same as that returned by time() and can be cast to a time_t and used in difftime. A millisecond is 1000 microseconds.

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

After you use difftime, calculate the difference in the microseconds field yourself.

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

回答by Alastair

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

如果您希望进行基准测试,您可能希望在 SO 上查看讨论该主题的其他一些线程

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

另外,请确保您了解准确度和精确度之间的区别。

回答by Peter

I think you will have to use something platform-specific. Hopefully that won't matter? eg. On Windows, look at QueryPerformanceCounter()which will give you something much better than milliseconds.

我认为您将不得不使用特定于平台的东西。希望这无关紧要?例如。在 Windows 上,看看QueryPerformanceCounter()哪个会给你比毫秒更好的东西。