zoukankan      html  css  js  c++  java
  • QueryPerformanceCounter与QueryPerformanceFrequency

    可以实现毫秒微秒计时器:

    在使用QueryPerformanceCounter之前和之后可得到一个高精度计时器值,然后使用QueryPerformanceFrequency得到每秒滴答数,最后将时差除以这个数可转换为秒。

    1 LARGE_INTEGER m_liPerformanceFrequency;
    2 QueryPerformanceFrequency( &m_liPerformanceFrequency);
    3 
    4 //...
    5 
    6 LARGE_INTEGER liPerformanceCount;
    7 QueryPerformanceCounter( &liPerformanceCount);
    8 double dTime = double(liPerformanceCount.QuadPart)/double(m_liPerformanceFrequency.QuadPart);

    对于IARGE_INTEGER union,可参考上一篇博文

    QueryPerformanceFrequency的函数原型为BOOL QueryPerformanceFrequency(LARGE_INTEGER *lpFrequency),返回硬件是否支持高精度计数器。

    QueryPerformanceCounter的函数原型为BOOL QueryPerformanceCounter (LARGE_INTEGER *lpCount)。

    下面给出具体例子:

     1 #include <windows.h>
     2 
     3 double PCFreq = 0.0;
     4 __int64 CounterStart = 0;
     5 
     6 void StartCounter()
     7 {
     8     LARGE_INTEGER li;
     9     if(!QueryPerformanceFrequency(&li))
    10     cout << "QueryPerformanceFrequency failed!
    ";
    11 
    12     PCFreq = double(li.QuadPart)/1000.0;
    13 
    14     QueryPerformanceCounter(&li);
    15     CounterStart = li.QuadPart;
    16 }
    17 double GetCounter()
    18 {
    19     LARGE_INTEGER li;
    20     QueryPerformanceCounter(&li);
    21     return double(li.QuadPart-CounterStart)/PCFreq;
    22 }
    23 
    24 int main()
    25 {
    26     StartCounter();
    27     Sleep(1000);
    28     cout << GetCounter() <<"
    ";
    29     return 0;
    30 }        
    

    得出结果应该接近windows睡眠了1000s。

    如果想要结果以秒为单位输出:

    PCFreq = double(li.QuadPart);

    或者以微秒为单位输出:

    PCFreq = double(li.QuadPart)/1000000.0;

    关于QueryPerformanceCounter的细节,msdn给出了文档:在关于时间代码中如何使用QueryPerformanceCounter?

  • 相关阅读:
    shell加载配置文件
    Shell四种运行方式(启动方式)
    Linux下Fork与Exec使用
    ln -snf 的个人理解
    利用python3将已有的某几个pptx文件的某些slides来生成新的pptx文件的范例
    如何在centos7中安装python3
    ng-include
    ng-class细说 by破狼
    AngularJS的Filter用法详解
    理解angularjs中的$emit,$broadcast和$on by Four
  • 原文地址:https://www.cnblogs.com/clairvoyant/p/5374240.html
Copyright © 2011-2022 走看看