Aman Neelappa
Aman Neelappa

Reputation: 13

CPU running time of a portion of code

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

Upvotes: 1

Views: 557

Answers (4)

sud03r
sud03r

Reputation: 19779

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.

Upvotes: 0

SimonJ
SimonJ

Reputation: 21306

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.

Upvotes: 4

Jonno_FTW
Jonno_FTW

Reputation: 8809

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

Upvotes: 0

Moshe Levi
Moshe Levi

Reputation: 3493

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

Upvotes: 0

Related Questions