Question

I looked through old threads but could not find the answer to my question:

How can I time the body of my function inside a C program?

Was it helpful?

Solution

A simple method is to use the 'clock' function:

#include <time.h>

clock_t start, end;
double cpu_time_used;

start = clock();
... /* Do whatever you want to time */
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;

Or if you're on linux you can use the 'time' command to time how long it takes your app to execute; this doesn't allow you to time a specific code section though, and includes time taken to initiate the process etc.

time ./myapp

Edit: This is very much a basic 'hack-in-a-quick-timer' approach. For true performance profiling you want to look at a proper profiler, as suggested by Larry Watanabe.

OTHER TIPS

It depends on your compiler and OS. On Sun workstations, I used to use "prof" or "gprof". There is surely a profiling tool for your compiler, OS, and machine - just google "C profile yourOS yourcompiler" (substitute the name of your OS and your compiler )

The basic method is using the clock() function, that is where we all started.

Ex.:


clock_t start = clock();
/* Your code */
printf("Time elapsed: %f\n", ((double)clock() - start) / CLOCKS_PER_SEC);

However, when you start learning about Operating systems, hardware, schedulers, multi-threading, etc. You realized that execution time is something very subjective. When you want to measure performance (which does not necessarily mean execution time) then you need more robust tools.

Gprof is a really easy to use C profiler, which could help you understand better the concept of performance.

time ./a.out

run above one, and output will be:

real    0m0.017s
user    0m0.017s
sys 0m0.000s

real: Total end to end time taken by program/command

user: Time taken in user mode.

sys: Time taken in kernel mode

Not sure about specific functions names in C, but a common practice is to store a microsecond timestamp before the body starts, then grab another one at the end and subtract.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top