• 如何输出高精度时间差


    昨天看核心编程看到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
    "),qwElapsedTime);
    }
        这段高精度代码原来是核心编程里的,,,
  • 相关阅读:
    Caffe2(1)----Ubantu14.04安装
    ROS知识(16)----如何编译时自动链接同一个工作空间的其他包的头文件(包含message,srv,action自动生成的头文件)
    GIT(4)----免输入账号和密码方法
    faceNet编译问题
    Python知识(7)--最小二乘求解
    BeanShell用法汇总(部分摘抄至网络)
    web_custom_request和web_submit_data
    创建一个数组,然后随机输出一个数组的值
    lr常见问题
    通过ctrl+r快速启动程序
  • 原文地址:https://www.cnblogs.com/zero5/p/3604031.html
Copyright © 2020-2023  润新知