Measuring amount of CPU time taken by a piece of code, in C on Unix/Linux

后端 未结 6 1020
旧时难觅i
旧时难觅i 2021-01-05 13:18

Can clock() be used as a dependable API to measure time taken by CPU to execute a snippet of code? When verified usng times() / clock(), both do not seem to measure the CPU

6条回答
  •  既然无缘
    2021-01-05 14:07

    On recent Linux's (*). you can get this information from the /proc filesystem. In the file /proc/PID/stat the 14th entry has the number of jiffies used in userland code and the 15th entry has the number of jiffies used in system code.

    If you want to see the data on a per-thread basis, you should reference the file /proc/PID/task/TID/stat instead.

    To convert jiffies to microseconds, you can use the following:

    define USEC_PER_SEC         1000000UL
    
    long long jiffies_to_microsecond(long long jiffies)
    {
        long hz = sysconf(_SC_CLK_TCK);
        if (hz <= USEC_PER_SEC && !(USEC_PER_SEC % hz))
        {
            return (USEC_PER_SEC / hz) * jiffies;
        }
        else if (hz > USEC_PER_SEC && !(hz % USEC_PER_SEC))
        {
            return (jiffies + (hz / USEC_PER_SEC) - 1) / (hz / USEC_PER_SEC);
        }
        else
        {
            return (jiffies * USEC_PER_SEC) / hz;
        }
    }
    

    If all you care about is the per-process statistics, getrusage is easier. But if you want to be prepared to do this on a per-thread basis, this technique is better as other then the file name, the code would be identical for getting the data per-process or per-thread.

    * - I'm not sure exactly when the stat file was introduced. You will need to verify your system has it.

提交回复
热议问题