Reputation: 11
#include <stdio.h>
#include <time.h>
int main()
{
time_t startTime, endTime;
while(1)
{
startTime = clock();
/*
Some processing
*/
endTime = clock();
gap = (int)((endTime - startTime) / (CLOCKS_PER_SEC));
printf("StartTime: %d, EndTime: %d\n", (int)startTime, (int)endTime);
printf("RunningTime: %d sec", gap);
}
}
Output:
StartTime: 1962, EndTime: 19247
RunningTime: 0 sec
I found out that this happens because CLOCKS_PER_SEC is 1,000,000 on Ubuntu.
Can I calculate CLOCKS_PER_SEC as 1,000 as in Windows?
Upvotes: 0
Views: 124
Reputation: 1
(I am focusing on Linux)
Read first time(7). Then read clock_gettime(2), getrusage(2), times(2), clock(3) (the notes are important).
There are several different notions of time: real, elapsed, process CPU, thread CPU. You need to choose the right one. Notice that some functions return time in seconds and microseconds or nanoseconds (using some struct
). You might want to convert them to a double
(and sometimes lose precision). Notice that real wall clock time might change (e.g. adjtimex(2)...) in some unexpected (non-monotonic) way.
On some cheap systems (notably 32 bits embedded Linux systems), be aware of the Y2038 problem
Can I calculate CLOCKS_PER_SEC as 1,000 as in Windows?
CLOCKS_PER_SEC
is semantically a constant that you cannot change (even on Windows). It is provided by the system (and on POSIX is required to be 1000000, so on Linux clock()
gives process CPU µs). See also sysconf(3) for _SC_CLK_TCK
(relevant for times(2)).
Upvotes: 1
Reputation: 409442
The problem is that endTime
, startTime
and CLOCKS_PER_SEC
are all integers. You need to cast at least one of the values to a floating point type. And use a floating point type for destination.
E.g.
double gap = (double) (endTime - startTime) / CLOCKS_PER_SEC;
printf("RunningTime: %f sec", gap);
Upvotes: 4