Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measuring time in C

Tags:

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?

like image 501
antonioalopezfernandez Avatar asked Oct 31 '12 10:10

antonioalopezfernandez


People also ask

How do I measure time in C?

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.

What does time () do in C?

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.

How do you calculate run time of a program?

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).

What is CLOCKS_PER_SEC in C?

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.


1 Answers

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.

like image 162
Fred Foo Avatar answered Sep 18 '22 18:09

Fred Foo