I am doing some execution in a function my_task
. I want to calculate how much time (or clock cycles) taken for CPU to execute this function, because I am going to do performance improvement on this function. So I refered windows API and written the below code.
typedef struct timer
{
LARGE_INTEGER t1;
LARGE_INTEGER t2;
LARGE_INTEGER frequency;
}MY_TIMER_S;
int start_timer(MY_TIMER_S *a)
{
QueryPerformanceFrequency(&a->frequency);
QueryPerformanceCounter(&a->t1);
}
int stop_timer(MY_TIMER_S *a)
{
double elsapsedtime;
QueryPerformanceCounter(&a->t2);
elapsedtime = (a->t2.QuadPart - a->t1.QuadPart) * 1000.0 / a->frequency.QuadPart;
printf("Elapsed time is %lf ms\n", elapsedtime);
}
void main()
{
MY_TIMER_S a = {0};
int i = 0;
for (i = 0; i < 3; i++)
{
start_timer(&a);
my_task();
stop_timer(&a);
}
}
Output is
Elapsed time is 0.113352 ms
Elapsed time is 0.203253 ms
Elapsed time is 0.104254 ms
These three values are accurate to nano seconds, but not precision. I thought like this because of process switching happened by other applications which is parallely runing in my system. I checked my task manager it was showing as 124 processes running. So I restarted my system (now 84 process in task manager) and then the output is
Elapsed time is 0.083162 ms
Elapsed time is 0.113223 ms
Elapsed time is 0.074258 ms
After than I executed my exe with start /high
command, then also I am not getting precision values.
My question is how to calculate an elapsed time of a function in more precision way in windows or linux.
Environment : 32 Bit Windows 7 on i5 processor, 4Gb ram with Visual Studio 2005 C compiler