Reputation: 923
int main(void){
int start = clock();
sleep(5);
int end = clock();
printf("%d", (end - start));
return 0;
}
When I execute this code in ubuntu, I get the result 30; however, I suspend the process in 5 seconds by sleep() method. Why is the result equal to 30 ?
How can I compute suspended time of the process ?
Upvotes: 0
Views: 27
Reputation: 15603
The clock()
function returns the amount of CPU time used since the process started. To get the number in seconds, you should divide by the constant CLOCKS_PER_SEC
.
In most cases, no or very little CPU time will be used in a call to sleep (I always get zero back).
You could use time()
to get seconds of wall clock time:
#include <stdio.h>
#include <time.h>
#include <unistd.h>
int main(void) {
time_t start = time(NULL);
sleep(5);
time_t end = time(NULL);
printf("%.1f\n", difftime(end, start));
return 0;
}
For timing short intervals gettimeofday()
may be more useful as it gives microsecond granularity instead of just seconds, like time()
.
Upvotes: 3