【问题标题】:Can I measure the CPU usage in Linux by thread into application我可以通过线程到应用程序中测量 Linux 中的 CPU 使用率吗
【发布时间】:2013-09-05 14:08:14
【问题描述】:

我有多线程 C 应用程序(守护程序)。我可以通过线程来测量我的应用程序的 CPU 使用率吗?

【问题讨论】:

    标签: c multithreading linux-kernel cpu-usage core


    【解决方案1】:

    虽然这是一个老问题,但它在我自己的 Google 搜索中却是相关热门。所以我会提供我想出的答案。

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

    您可以使用pthread_getcpuclockidclock_gettime
    手册页链接pthread_getcpuclockidclock_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);
    }
    

    【讨论】:

      【解决方案2】:

      您可以解析出/proc/<PID>/stat 中的数据。 CPU线是这样的:-

      cpu  143359 8217 480152 132054567 45162 5678 24656 0 0
      

      【讨论】:

      • 我有一个进程和一个 pid 和许多线程。每个线程都获得传入连接并开始工作。我为我开发了线程监控和有趣的信息“thead 是如何加载的”
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-16
      相关资源
      最近更新 更多