¶ CPU使用率
¶ pidstat (推荐)
pidstat -p 进程PID -H -u 间隔秒数 | awk '{if(NR>3){print $1,$8}}' |
-H
: Display timestamp in seconds since the epoch.-u
: Report CPU utilization.NR>3
: 第四行开始才是有效输出。
awk可能需要加上fflush(stdout)
: awk fflush
¶ top
top -b -p 进程PID -d 间隔秒数 |
-b
: Batch mode.
配合awk
等可以把CPU使用率给提取出来,但是由于CPU使用率在哪一列是根据~/.toprc
确定的,所以要做到portable很麻烦。
¶ ps (不推荐)
注意,这个方法只能用来获取整个进程生命周期的平均CPU使用率。
ps -q 进程PID -o %cpu |
输出:
%CPU |
%cpu %CPU cpu utilization of the process in "##.#" format. Currently, it is the CPU time used |
¶ 累积CPU time
¶ C/C++:
clock_gettime
获取当前进程的CPU时间戳:
static inline time_t process_cpu_timestamp_ns() { |
两个CPU时间戳相减就是中间进程消耗的CPU time。
¶ ps
累积CPU time的秒数:
ps -q 进程PID -o cputimes |
cputimes TIME cumulative CPU time in seconds (alias times). |