开发者

c++ thread running time

开发者 https://www.devze.com 2022-12-28 08:17 出处:网络
I want to know whether I can calculate the running time for each thread. I implement a multithread program in C++ using pthread.

I want to know whether I can calculate the running time for each thread. I implement a multithread program in C++ using pthread. As we know, each thread will compete the CPU. Can I use clock() function to calculate the actual number of CPU clocks each thread consumes?

my program looks like:

Class Thread ()
{
Start();
Run();
Computing();
};

Start() is to start multiple threads. Then each thread will run Computing function to do something. My question is how I can calculate t开发者_StackOverflow社区he running time of each thread for Computing function


No, you cannot use clock. Processor could switch to another thread between Start and Computing calls so you will calculate the time of several threads. You need to use tick counter local for one thread.


according to clock_gettime(3):

Sufficiently recent versions of GNU libc and the Linux kernel support the following clocks: CLOCK_REALTIME System-wide realtime clock. Setting this clock requires appropriate privileges.

CLOCK_MONOTONIC Clock that cannot be set and represents monotonic time since some unspecified starting point.

CLOCK_PROCESS_CPUTIME_ID High-resolution per-process timer from the CPU.

CLOCK_THREAD_CPUTIME_ID Thread-specific CPU-time clock.

so you may have CLOCK_THREAD_CPUTIME_ID a try.


What platform are you using? If you are using Linux and are on kernel > 2.6.26 you can use the RUSAGE_THREAD flag to getrusage:

struct rusage usage
getrusage(RUSAGE_THREAD, &usage);

within struct rusage, you'll find ru_utime and ru_stime which tracks user time and system time respectively. Call this once at the beginning and once after and you can get the delta.

0

精彩评论

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