I have read several forums with the same title, although what I am after is NOT a way to find out how long it takes my computer to execute the program. I am interested in finding out how long the program is in use by the user. I have looked at several functions inside #include <time.h>, however, it seems as though these functions (like clock_t) give the time it takes for my computer to execute my code which is not what I am after.
Thank you for your time.
EDIT:
I have done:
clock_t start, stop; long int x; double duration; start = clock(); //code stop = clock(); // get number of ticks after loop // calculate time taken for loop duration = ( double ) ( stop - start ) / CLOCKS_PER_SEC; printf( "\nThe number of seconds for loop to run was %.2lf\n", duration ); I receive 0.16 from the program, however, when i timed it I got 1 minute and 14 seconds. how does this possibly add up?
22 Answers
The clock function counts CPU time used, not elapsed time. For a program that's 100% CPU-intensive, the time reported by clock will be close to wall time, but otherwise it's likely to be less -- often much less.
One easy way of measuring elapsed or "wall clock" time is with the time function:
time_t start, stop; start = time(NULL); // code stop = time(NULL); printf("The number of seconds for loop to run was %ld\n", stop - start); This is a POSIX function, though -- it's not part of the core C standards, and it may not exist on, say, embedded versions of C.
1I think you're looking for getrusage() function. It doesn't give you time consumed like how you use a stop-watch to time a function.
The function gives overall resource usage of the current program and splits it per-user. This is what the time command gives.