As the name suggests, I have a problem with the clock() function.
I want the time of each step in the loop to be printed.
For example, I have code:
#include<time.h>
int main()
{
clock_t start,end;
for(int i=0;i<number_of_elements;i )
{
start=clock();
for(int z=/*something*/;z>=0;z--)
{
//Some desired processing
}
for(int g=0;g</*something*/;g )
{
//Some desired processing
}
end=clock();
double duration=(double)(end-start)/CLOCKS_PER_SEC;
printf("%d.step %f\n",i 1,duration);
}
}
And now I want to print the time of each step from 'i' in this loop. But what I get are only zeros.
Example:
1.step 0.000000
2.step 0.000000
3.step 0.000000
4.step 0.000000
etc.
Can anyone help me about this?
Thanks in advance!
CodePudding user response:
I tried out your code template with this
#include<time.h>
int main()
{
clock_t start,end;
for(int i=0;i<5;i )
{
start=clock();
for(int z=3;z>=0;z--)
{
printf("\n");
}
for(int g=0;g<3;g )
{
printf("\n");
}
end=clock();
double duration=(double)(end-start)/CLOCKS_PER_SEC;
printf("%d.step %f\n",i 1,duration);
}
}
And the output was this:
1.step 0.000077
2.step 0.000005
3.step 0.000009
4.step 0.000006
5.step 0.000009
It seems to work perfectly fine.
Maybe the code that you executed in the for
loops was too small to take any time?
CodePudding user response:
Look at man clock
CONFORMING TO
C89, C99, POSIX.1-2001. POSIX requires that CLOCKS_PER_SEC equals 1000000 independent of the actual resolution.
cppreference says:
Notes
POSIX defines CLOCKS_PER_SEC as one million, regardless of the actual precision of clock.
That means, microseconds, you could do better via clock_gettime with the clock CLOCK_PROCESS_CPUTIME_ID
. Based on your implementation, nanosecond precision could be possible.
Note: clock_gettime
is not C standard, conforms to POSIX.