如何输出高精度时间差

来源:互联网 发布:mac ps2017怎么破解 编辑:程序博客网 时间:2024/06/06 13:15
昨天看核心编程看到171页,看到了GetThreadTimes,结果按书上的源码运行无法获取时间向师傅求助,师傅告诉我
猪头三 22:25:44你看到的时间一样,是因为你的 时间精度不够猪头三 22:25:56你应该要更加高精度的时间获取
于是搜到到这篇
http://zhidao.baidu.com/question/85502612.html#281447-qzone-1-49353-2b4b15c6dbd92b17940ffe005c9ace27请教VC++高手 如何输出高精度时间差
文中高手回答到
晕了,想钱想疯了也就算了,百度的分数也嫌多嫌少的,开了眼了.楼主到MSDN里看下这两个函数:
BOOL QueryPerformanceFrequency(LARGE_INTEGER* lpFrequency);BOOL QueryPerformanceCounter(LARGE_INTEGER* lpPerformanceCount);
  
另外给你个实现类:
class CStopwatch {public:CStopwatch() { QueryPerformanceFrequency(&m_liPerfFreq); Start();}void Start() { QueryPerformanceCounter(&m_liPerfStart); }__int64 Now() const {LARGE_INTEGER liPerfNow;QueryPerformanceCounter(&liPerfNow);return (((liPerfNow.QuadPart - m_liPerfStart.QuadPart) * 1000) / m_liPerfFreq.QuadPart);}private:LARGE_INTEGER m_liPerfFreq;LARGE_INTEGER m_liPerfStart;};
  
在Now函数里,有个乘数是1000,目的是让Now返回的时间为毫秒。使用:
 
CStopwatch stopwatch;//do the work that would take long time;__int64 qwElapsedTime = stopwatch.Now();//qwElapsedTime indicates how long the work has spent;
 
注意,因为是高精度时间,因此,你要做的工作应该是短期内能完成的工作,时间太长,误差会特别大,因为线程有占用时间片的因素存在。
 测试成功获取代码运行时间我的程序代码如下
#include <stdio.h>#include <tchar.h>#include <Windows.h>#include <Locale.h>class CStopwatch {public:CStopwatch() { QueryPerformanceFrequency(&m_liPerfFreq); Start(); }void Start() { QueryPerformanceCounter(&m_liPerfStart); }__int64 Now() const {LARGE_INTEGER liPerfNow;QueryPerformanceCounter(&liPerfNow);return (((liPerfNow.QuadPart - m_liPerfStart.QuadPart) * 1000) / m_liPerfFreq.QuadPart);}private:LARGE_INTEGER m_liPerfFreq;LARGE_INTEGER m_liPerfStart;};void PerformLongOperation();int _tmain(int argc, _TCHAR* argv[]){_wsetlocale(LC_ALL, L"chs"); //本地化PerformLongOperation();return 0;}void PerformLongOperation(){CStopwatch stopwatch;//执行运算代码Sleep(5000);__int64 qwElapsedTime = stopwatch.Now();_tprintf(TEXT("总执行时间%lld\n"),qwElapsedTime);}
  这段高精度代码原来是核心编程里的,,,
0 0