I'm trying to measure some activity in C (Matrix multiplying) and noticed that I should do something like this:
clock_t start = clock();
sleep(3);
clock_t end = clock();
double elapsed_time = (end - start)/(double)CLOCKS_PER_SEC;
printf("Elapsed time: %.2f.\n", elapsed_time);
The output is:
Elapsed time: 0.00.
Why is this happening?
To get the elapsed time, we can get the time using clock() at the beginning, and at the end of the tasks, then subtract the values to get the differences. After that, we will divide the difference by CLOCK_PER_SEC (Number of clock ticks per second) to get the processor time.
C library function - time() The C library function time_t time(time_t *seconds) returns the time since the Epoch (00:00:00 UTC, January 1, 1970), measured in seconds. If seconds is not NULL, the return value is also stored in variable seconds.
To calculate the running time, find the maximum number of nested loops that go through a significant portion of the input. Some algorithms use nested loops where the outer loop goes through an input n while the inner loop goes through a different input m. The time complexity in such cases is O(nm).
CLOCKS_PER_SEC is a macro in C language and is defined in the <time.h> header file. It is an expression of type, as shown below: clock_t clock(void) CLOCKS_PER_SEC defines the number of clock ticks per second for a particular machine.
clock
estimates the CPU time used by your program; that's the time the CPU has been busy executing instructions belonging to your program. sleep
doesn't perform any work, so it takes no noticeable CPU time (even if it takes wallclock time).
If you want to measure wallclock time, use time
:
time_t start = time(NULL);
sleep(3);
printf("%.2f\n", (double)(time(NULL) - start));
will print a number close to three.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With