You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
arthas/tutorials/katacoda/command-thread-cn/CPU-ratios-calculate.md

16 lines
1.2 KiB
Markdown

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

### cpu使用率是如何统计出来的
这里的cpu使用率与linux 命令`top -H -p <pid>` 的线程`%CPU`类似一段采样间隔时间内当前JVM里各个线程的增量cpu时间与采样间隔时间的比例。
> 工作原理说明:
* 首先第一次采样获取所有线程的CPU时间(调用的是`java.lang.management.ThreadMXBean#getThreadCpuTime()`及`sun.management.HotspotThreadMBean.getInternalThreadCpuTimes()`接口)
* 然后睡眠等待一个间隔时间默认为200ms可以通过`-i`指定间隔时间)
* 再次第二次采样获取所有线程的CPU时间对比两次采样数据计算出每个线程的增量CPU时间
* 线程CPU使用率 = 线程增量CPU时间 / 采样间隔时间 * 100%
> 注意: 这个统计也会产生一定的开销JDK这个接口本身开销比较大因此会看到as的线程占用一定的百分比为了降低统计自身的开销带来的影响可以把采样间隔拉长一些比如5000毫秒。
> 另外一种查看Java进程的线程cpu使用率方法可以使用[`show-busy-java-threads`](https://github.com/oldratlee/useful-scripts/blob/dev-2.x/docs/java.md#-show-busy-java-threads)这个脚本。