1

I am working on a server program written in C written as a procedural (not OO) code. Every method implements some specific functionality. For the diagnostics purpose I want to add code to a bunch of methods that will calculate and print the running time for the respective functions. It is on linux and I know how to calculate the running time.

My question is what would be the best, most efficient way to code this?

because it is a procedural code written in C I will have to add code to all the (about 20) functions for timer start, timer end and calculate the difference. Is there a better way than this ?

punekr12
  • 653
  • 2
  • 7
  • 14
  • 2
    Why don't you write a function or macro that contains your timing code and wrap your function calls with that? – Carl Norum Jul 22 '13 at 20:43
  • Add the program level or the procedure level? If it's program, you can use time. If at procedure level, call time, retain value, call again after procedure and note ticks elapsed. – Jiminion Jul 22 '13 at 20:45
  • @CarlNorum even then I have to add the two function calls to every function. But then that's what I might eventually do – punekr12 Jul 22 '13 at 21:06
  • I'm not sure I follow; wouldn't you put that stuff in the macro? – Carl Norum Jul 22 '13 at 21:07
  • Maybe just add one call after every function that calculates the previous time and sets up for the next time. You'd need to initiate it and terminate it with 2 other calls. – Jiminion Jul 22 '13 at 21:10

2 Answers2

0

You may use external profiler tool for this need. gprof is a well-known standard tool. Here is the simple use example:

$ gcc -pg a.c -o a
$ ./a
$ gprof

This tool displays total running time (absolute and percentage) of each function.

However, this is almost useless if you need this information in runtime.

Ivan Smirnov
  • 4,365
  • 19
  • 30
0
#include<time.h>
.
.
.
clock_t start, end, total;
start = clock();
.
.
.
end = clock();
total = (double) (start - end) / CLOCKS_PER_SEC;

This will give you the execution time in seconds. You can even put this into macros and wrap it around the functions.

ctrl-shift-esc
  • 876
  • 1
  • 9
  • 19