QueryPerformanceCounter返回负数

时间:2013-03-20 18:11:17

标签: c++ performancecounter

嘿我试图计算函数执行所需的时间 我是这样做的: 的 Timer.cpp

long long int Timer :: clock1()
{
    QueryPerformanceCounter((LARGE_INTEGER*)&time1);
    return time1;
}
long long int Timer :: clock2()
{
    QueryPerformanceCounter((LARGE_INTEGER*)&time2);
    return time2;
}

的main.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;
}

有人能告诉我,我是否正确地这样做了吗?

2 个答案:

答案 0 :(得分:1)

你是从开始时间减去结束时间。

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

应该是

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

答案 1 :(得分:1)

假设我在10秒钟开始玩,30秒结束。花了多长时间? 20秒为此,我们会做30 - 10;也就是说,第二次减去第一次。

所以也许你想要:

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