开发者

CPU running time of a portion of code

开发者 https://www.devze.com 2022-12-12 17:37 出处:网络
I would like to know the CP开发者_Go百科U 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

I would like to know the CP开发者_Go百科U 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


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.


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消