QueryPerformanceCounter 返回负数

Posted

技术标签:

【中文标题】QueryPerformanceCounter 返回负数【英文标题】:QueryPerformanceCounter returning negative number 【发布时间】:2013-03-20 18:11:16 【问题描述】:

嘿,我想计算函数执行需要多长时间 我这样做是这样的: Timer.cpp

long long int Timer :: clock1()

    QueryPerformanceCounter((LARGE_INTEGER*)&time1);
    return time1;

long long int Timer :: clock2()

    QueryPerformanceCounter((LARGE_INTEGER*)&time2);
    return time2;

ma​​in.cpp

#include "Timer.h"  //To allow the use of the timer class.

Timer query;

void print()

    query.clock1();
    //Loop through the elements in the array.
    for(int index = 0; index < num_elements; index++)
    
        //Print out the array index and the arrays elements.
        cout <<"Index: " << index << "\tElement: " << m_array[index]<<endl;
    
    //Prints out the number of elements and the size of the array.
    cout<< "\nNumber of elements: " << num_elements;
    cout<< "\nSize of the array: " << size << "\n";
    query.clock2();
    cout << "\nTime Taken : " << query.time1 - query.time2;

谁能告诉我这样做是否正确?

【问题讨论】:

如果time2 更大,query.time1 - query.time2 将是负数,对吧? 正确,但我还能如何实现这两个变量的差异? query.time2 - query.time1 【参考方案1】:

您正在从开始时间中减去结束时间。

cout << "\nTime Taken : " << query.time1 - query.time2;

应该是

cout << "\nTime Taken : " << query.time2 - query.time1

【讨论】:

【参考方案2】:

假设我在 10 秒开始某件事,然后在 30 秒结束。花了多长时间? 20 秒。要做到这一点,我们会做30 - 10;即第二次减去第一次。

所以也许你想要:

cout << "\nTime Taken : " << (query.time2 - query.time1);

【讨论】:

以上是关于QueryPerformanceCounter 返回负数的主要内容,如果未能解决你的问题,请参考以下文章

QueryPerformanceCounter 运行时错误

为啥与两者相比得到不同的毫秒值(QTIme 和 QueryPerformanceCounter)

QueryPerformanceCounter 是不是保证在启动后给您时间?

QueryPerformanceCounter 抛出不正确的数字

QueryPerformanceCounter 和奇怪的结果

QueryPerformanceCounter 状态?