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