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位整数),这显然存在整数溢出的一些问题,但这可能不是常见的情况.
如果你正在使用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)
时钟功能为您提供毫秒计时器,但它不是最好的.它的真正分辨率取决于您的系统.你可以试试
#include <time.h>
int clo = clock();
//do stuff
cout << (clock() - clo) << endl;
Run Code Online (Sandbox Code Playgroud)
并看看你的结果如何.