如何计算每个HTTP请求的CPU使用率

I want to get the CPU usage of each individual request sent to my local Apache server. I am using top to capture the CPU usage but it is not that reliable, because most of the times it captures 0 as CPU usage. I have checked utilities like psutil etc but they did not work?

Is there anyway (some code or package in Go) that can be helpful in this regard? P.S the best way for me would be if I can't get CPU usage in access.log file?

The percentage (CPU load) - no matter how you collect it - will always be a point-in-time sample. It's useful for determining what process is using more of the CPU at a given moment, it's useful for profiling a program to see which parts use a greater proportion of CPU over the course of an execution, but it's completely useless for knowing how much CPU a request consumes; that cannot be measured in CPU% at all. Even if you managed to calculate it, "a request uses 5% CPU" is meaningless - does it use 5% for a nanosecond? For an hour? What you want to measure for something like this is CPU time: how long the CPU was actively in use by your process.

CPU load is basically calculated as: in the last sample period (say, 1 second), how much of the time was the CPU executing instructions for this process. CPU time is the core of that metric: how much time did the CPU spend executing instructions for this process. That's a metric you can meaningfully use for finding profiling targets for optimization, capacity planning, performance benchmarking, and so on.

The quickest way to get that info would be to restart the service, generate a known level of load (say, 100k requests), check the CPU time of the process (e.g. as shown in top) at the end, and divide that by the request count. That would tell you how much CPU time a request consumes.