Compute how long it takes todo something

Started by
10 comments, last by Anddos 11 years, 3 months ago
If you want to test how many seconds it ran for, you can do this:
DWORD WINAPI test_thread(LPVOID Param)
{
    MessageBox(NULL,"test_thread started ","",0);

    time_t startTime = time();

    for(int i = 0; i < 99999999999; i++)
    {
        //WARNING! If you don't have anything in this loop, your compiler might optimize the entire loop into non-existence.
    }
     
    time_t endTime = time();
    time_t numSeconds = (endTime - startTime);

    //numSeconds is the number of seconds. You could cast it to unsigned int or int.
    
    MessageBox(NULL,"test_thread over","",0);

    return 0;
}
No, time() is not "high performance". time() returns seconds. You can use the RunTime() function I posted above for millaseconds (1/1000 of a second), which is still not considered "high performance" but is perfectly fine for most uses and what I usually use. When people say 'high performance' they usually mean microseconds (1/1000000 of a second).

There is no cross-platform way to get guaranteed microsecond performance, but C++11 has a few classes for getting microseconds if it's available, and millaseconds if it's not. Win32 also has some microsecond precision timers, if I recall correctly, but they are Windows-only.

Here is the same test as above, but with millasecond performance, if you need it:
DWORD WINAPI test_thread(LPVOID Param)
{
    MessageBox(NULL,"test_thread started ","",0);

    unsigned int startTime = RunTime();

    for(int i = 0; i < 99999999999; i++)
    {
        //WARNING! If you don't have anything in this loop, your compiler might optimize the entire loop into non-existence.
    }
     
    unsigned int endTime = RunTime();
    unsigned int millaseconds = (endTime - startTime);

    //Some conversion examples:
    unsigned int seconds = (millaseconds / 1000); //1000 millaseconds in a second.
    millaseconds %= 1000;
    unsigned int minutes = (seconds / 60); //60 seconds in a minute.
    seconds %= 60;
    unsigned int hours = (minutes / 60); //60 minutes in an hour.
    minutes %= 60;

    //Example: "It took: 0 hours, 2 minutes, 24 seconds, and 456 millaseconds."
    std::cout << "It took: " << hours << " hours, " << minutes << " minutes, " << seconds << " seconds, and " << millaseconds << " millaseconds." << std::endl;
    
    MessageBox(NULL,"test_thread over","",0);

    return 0;
}
Advertisement

wow that us fantastic information mate

:)

This topic is closed to new replies.

Advertisement