我可以通过线程到应用程序来测量Linux中的CPU使用率

use*_*692 3 c multithreading core cpu-usage linux-kernel

我有多线程C应用程序(守护进程).我可以通过线程测量我的应用程序的CPU使用率.

Sam*_*man 6

虽然这是一个古老的问题,但它在我自己的谷歌搜索中成为最重要的打击.所以我会提供我想出的答案.

假设您正在使用pthread或使用它的库,例如Boost库.

你可以使用pthread_getcpuclockidclock_gettime.
手册页链接pthread_getcpuclockid,clock_gettime.

这是一个将当前时间作为double返回的简单示例.

double cpuNow( void ) {
    struct timespec ts;
    clockid_t cid;

    pthread_getcpuclockid(pthread_self(), &cid);
    clock_gettime(cid, &ts);
    return ts.tv_sec + (((double)ts.tv_nsec)*0.000000001);
}
Run Code Online (Sandbox Code Playgroud)