How to measure function running time in Qt? - c++

I am calling argon2 - memory intensive hashing function in Qt and measuring its running time:
...
QTime start = QTime::currentTime();
// call hashing function
QTime finish = QTime::currentTime();
time = start.msecsTo(finish) / 1000.0;
...
In argon2 library's test case, time is measured in another way:
...
clock_t start = clock();
// call hashing function
clock_t finish = clock();
time = ((double)finish - start) / CLOCKS_PER_SEC;
...
I am calling the function exactly as they call in their test case. But I am getting a twice bigger number (twice slower). Why? How to measure function running time in Qt? What clock() actually measures?
env:virtualBox, Ubuntu14.04 64bit, Qt5.2.1, Qt Creator 3.0.1.

You could also try to use the QElapsedTimer:
QElapsedTimer timer;
timer.start();
slowOperation1();
qDebug() << "The slow operation took" << timer.elapsed() << "milliseconds";
qDebug() << "The slow operation took" << timer.nsecsElapsed() << "nanoseconds";
Documentation of QElapsed Timer

clock() isn't accurate for measuring time spend in functions. It just returns number of ticks for whole program while its on CPU rightnow, it doesn't count blocking IO operations or sleeps. It just counts ticks which your program is running on CPU (processing). If you put sleep in your code you will loose CPU and this time isn't counting with clock().
You have to use time() or gettimeofday() or more accurate rdtsc assembly instruction.
Lookat these questions :
clock() accuracy
Why is CLOCKS_PER_SEC not the actual number of clocks per second?
In Qt sources, you will see the Qt has used gettimeofday for implementing QTime::currentTime() under Unix
https://github.com/radekp/qt/blob/master/src/corelib/tools/qdatetime.cpp : line 1854

Related

std::chrono gives abnormal value when I use cpulimit to limt the program

My code is like:
while(1)
{
std::cout << "local time " << std::chrono<<std::chrono::duration_cast<std::chrono::milliseconds>((std::chrono::steady_clock::now()).time_since_epoch()).count() << "\n";
clock_t t1, t2;
t1 = clock();
std::chrono::steady_clock::time_point t3 = std::chrono::steady_clock::now(), t4;
MyProcessFunc();
t4 = std::chrono::steady_clock::now();
t2 = clock();
std::cout << "process chrono time " << std::chrono::duration_cast<std::chrono::milliseconds>(t4 - t3).count() << "ms\n";
std::cout << "process clock time " << 1000.0*(t2 - t1)/CLOCKS_PER_SEC << "ms\n";
}
And when this program is running, I use "taskset" and "cpulimit" to restrict it to using only a single core of CPU and about 10% of this single core. Then I found chrono gives werid values:
local time 352398168
process chrono time 28ms
process clock time 26.829ms
local time 352398196
process chrono time 808ms
process clock time 26.934ms
local time 352399004
process chrono time 28ms
process clock time 27.168ms
local time 352399032
process chrono time 28ms
process clock time 27ms
local time 352399061
process chrono time 27ms
process clock time 26.931ms
local time 352399089
process chrono time 809ms
process clock time 30.479ms
local time 352399898
process chrono time 33ms
process clock time 32.135ms
I can feel the stutter of the program running, so may be chrono's result is right. But I think there are definitely other places that block the running of the program. The main part of the time consuming is not on my program.
Any one knows why plz
clock() returns the time actually consumed by your program, see here, while std::chrono::steady_clock keeps counting even when your program is not running.
This explains your results.

Know if CPU supports nanoseconds

I am trying to get elapsed time in nanoseconds using C++ in visual studio. I did some testing and the measures always end with 00. Does it mean that my processor (Ryzen 7-1800X) doesn't support ~1 nanosecond resolution but only ~100ns? Can I enable it somehow?
auto start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < 10; i++) {
//stuff
auto elapsed = std::chrono::high_resolution_clock::now() - start;
long long nanoseconds = std::chrono::duration_cast<std::chrono::nanoseconds>(elapsed).count();
std::cout << "\n" << nanoseconds << "\n";
}
In MSVC 2015+ std::chrono::high_resolution_clock is based on QueryPerformanceCounter, which has a 100ns resolution.
On Windows, QueryPerformanceCounter is the fastest userland timer.
If you want an even higher resolution, you can try the RDTSC instruction (__rdtsc) which returns the CPU cycle counter. But it's a very tricky one to use properly and is not recommended.
It seems on Windows you're pretty much stuck to a 100ns resolution. Keep in mind that in Windows world 100ns is a very short time - it equals roughly 300 instructions. Just one call to QueryPerformanceCounter already takes around 1000 instructions.

How to calculate compile time, execution time ,performance and success measure of a test?

I have c++ program in that i want to have compiletime, execution time ,performance measure and success measure of a test.Right now i am calculating time as follows:
clock_t starts = clock();
test_case();
clock_t ends = clock();
double time = (double)(ends - starts);
But i dont know wether "time" is compile time or execution time. If it is compile time then how will i get execution time or if it is execution time how will i get its compile time. Also, i need to have performance and success mesure of the "test_case()". So, suggest me how will i get it.
The time that you are calculating is the execution time. clock() returns the number of clock ticks since your program started. Hence taking the difference of starts and ends will give you execution time of test_case() in second multiplied by CLOCKS_PER_SEC. CLOCKS_PER_SEC is the number of clock ticks per second.
Compile time calculation can be done using template metaprogramming.
To get a view template metaprogramming, have a look at: Compile Time Calculation
If you are using UNIX, you can easily get compilation time using command like:
time g++ file_name.cpp
This will output the time required by g++ file_name.cpp to compile.
The above function outputs the execution time. I would prefer to use query performance counter for finding the execution time.
However, we can find the build time if we are using a VC++ compiler.
The option can be found at Tools->Options->VC++ProjectSettings->BuildTime
The time is execution time, because it get by the ends and starts.But the function clock() is not a good way for caculate codes' execution time, for its low accuracy(maybe ms).
I suggest you use c++ STL chrono, you will get more accurate output.Example:
int main()
{
chrono::high_resolution_clock::time_point begin_time = chrono::high_resolution_clock::now();
for(int i=0;i<100000;i++)
{
//do something
;
}
chrono:: high_resolution_clock::time_point stop_time = chrono::high_resolution_clock::now();
chrono::duration<double> slapsed = duration_cast<duration<double>>(stop_time - begin_time);
cout << "time takes " << slapsed.count() * 1000 << "ms" << endl;
return 0;
}
I hope this can help you.

Calculating time length between operations in c++

The program is a middleware between a database and application. For each database access I most calculate the time length in milliseconds. The example bellow is using TDateTime from Builder library. I must, as far as possible, only use standard c++ libraries.
AnsiString TimeInMilliseconds(TDateTime t) {
Word Hour, Min, Sec, MSec;
DecodeTime(t, Hour, Min, Sec, MSec);
long ms = MSec + Sec * 1000 + Min * 1000 * 60 + Hour * 1000 * 60 * 60;
return IntToStr(ms);
}
// computing times
TDateTime SelectStart = Now();
sql_manipulation_statement();
TDateTime SelectEnd = Now();
On both Windows and POSIX-compliant systems (Linux, OSX, etc.), you can calculate the time in 1/CLOCKS_PER_SEC (timer ticks) for a call using clock() found in <ctime>. The return value from that call will be the elapsed time since the program started running in milliseconds. Two calls to clock() can then be subtracted from each other to calculate the running time of a given block of code.
So for example:
#include <ctime>
#include <cstdio>
clock_t time_a = clock();
//...run block of code
clock_t time_b = clock();
if (time_a == ((clock_t)-1) || time_b == ((clock_t)-1))
{
perror("Unable to calculate elapsed time");
}
else
{
unsigned int total_time_ticks = (unsigned int)(time_b - time_a);
}
Edit: You are not going to be able to directly compare the timings from a POSIX-compliant platform to a Windows platform because on Windows clock() measures the the wall-clock time, where-as on a POSIX system, it measures elapsed CPU time. But it is a function in a standard C++ library, and for comparing performance between different blocks of code on the same platform, should fit your needs.
On windows you can use GetTickCount (MSDN) Which will give the number of milliseconds that have elapsed since the system was started. Using this before and after the call you get the amount of milliseconds the call took.
DWORD start = GetTickCount();
//Do your stuff
DWORD end = GetTickCount();
cout << "the call took " << (end - start) << " ms";
Edit:
As Jason mentioned, Clock(); would be better because it is not related to Windows only.

How to get system time in C++?

In fact i am trying to calculate the time a function takes to complete in my program.
So i am using the logic to get system time when i call the function and time when the function returns a value then by subtracting the values i get time it took to complete.
So if anyone can tell me some better approach or just how to get system time at an instance it would be quite a help
The approach I use when timing my code is the time() function. It returns a single numeric value to you representing the epoch which makes the subtraction part easier for calculation.
Relevant code:
#include <time.h>
#include <iostream>
int main (int argc, char *argv[]) {
int startTime, endTime, totalTime;
startTime = time(NULL);
/* relevant code to benchmark in here */
endTime = time(NULL);
totalTime = endTime - startTime;
std::cout << "Runtime: " << totalTime << " seconds.";
return 0;
}
Keep in mind this is user time. For CPU, time see Ben's reply.
Your question is totally dependant on WHICH system you are using. Each system has its own functions for getting the current time. For finding out how long the system has been running, you'd want to access one of the "high resolution performance counters". If you don't use a performance counter, you are usually limited to microsecond accuracy (or worse) which is almost useless in profiling the speed of a function.
In Windows, you can access the counter via the 'QueryPerformanceCounter()' function. This returns an arbitrary number that is different on each processor. To find out how many ticks in the counter == 1 second, call 'QueryPerformanceFrequency()'.
If you're coding under a platform other than windows, just google performance counter and the system you are coding under, and it should tell you how you can access the counter.
Edit (clarification)
This is c++, just include windows.h and import the "Kernel32.lib" (seems to have removed my hyperlink, check out the documentation at: http://msdn.microsoft.com/en-us/library/ms644904.aspx). For C#, you can use the "System.Diagnostics.PerformanceCounter" class.
You can use time_t
Under Linux, try gettimeofday() for microsecond resolution, or clock_gettime() for nanosecond resolution.
(Of course the actual clock may have a coarser resolution.)
In some system you don't have access to the time.h header. Therefore, you can use the following code snippet to find out how long does it take for your program to run, with the accuracy of seconds.
void function()
{
time_t currentTime;
time(&currentTime);
int startTime = currentTime;
/* Your program starts from here */
time(&currentTime);
int timeElapsed = currentTime - startTime;
cout<<"It took "<<timeElapsed<<" seconds to run the program"<<endl;
}
You can use the solution with std::chrono described here: Getting an accurate execution time in C++ (micro seconds) you will have much better accuracy in your measurement. Usually we measure code execution in the round of the milliseconds (ms) or even microseconds (us).
#include <chrono>
#include <iostream>
...
[YOUR METHOD/FUNCTION STARTING HERE]
auto start = std::chrono::high_resolution_clock::now();
[YOUR TEST CODE HERE]
auto elapsed = std::chrono::high_resolution_clock::now() - start;
long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count();
std::cout << "Elapsed time: " << microseconds << " ms;