简体   繁体   中英

QueryPerformanceCounter returning negative number

Hey im trying to count how long the function takes to execute I am doing it like this: 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;
}

Can anyone tell me if i am doing this correctly?

You are substracting ending time from starting time.

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

should be

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

Let's say I start something at 10 seconds and it finishes at 30 seconds. How long did it take? 20 seconds. To get that, we would do 30 - 10 ; that is, the second time subtract the first time.

So perhaps you want:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM