tags:

views:

110

answers:

4

Hi

I would like to know the CPU time used by a portion of code.( I am aware of the time command in linux, but that would give me the running time of the complete program, not a portion of it.) Is there any function/command that can help me achieve this.

Thanks

+4  A: 

The clock() function in the standard C library gives the amount of CPU time used since the process started, so you can compare "before" and "after" values to get the time used:

#include <time.h>
#include <stdio.h>

...

clock_t t0, t1;

t0 = clock();
// do computation
t1 = clock();

printf("Computation took %dms\n", (int)((t1-t0) * 1000 / CLOCKS_PER_SEC));

Other languages will have similar functions as well as profilers for more advanced timing info; post more details if you have a particular target in mind.

SimonJ
A: 

When I developed software on linux I used Callgrind and KCachegrind to profile my code. it can show you how much time a single method took out of the total execution time of the program and much more.

Another option is to check it yourself by wrapping the relevant code with some timing functions like gettimeofday().

Moshe Levi
gettimeofday() gives the wall-clock time while i need the CPU time. I will try the profiling software you suggestedThanks.
Aman Neelappa
Yep, you are right. as I said, I'm a bit rusty on Linux stuff :) I would still recommend using Callgrind as part of your development process though.
Moshe Levi
A: 

In C/C++:
http://www.gnu.org/s/libc/manual/html_node/CPU-Time.html
This way in java

P.S: these two are first results of google.

Also, if you are interested in measuring CPU cycles instead of CPU time, you can use this.

Neeraj
I guess i was using the wrong search queries.Thanks anyways :)
Aman Neelappa
A: 

In Haskell, you could implement the getCPUtime monad to get the time difference between functions in the main part of the code.

Jonno_FTW