社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
1.简介
一个程序,完成它预设的功能,并不能说明它是一个优良的程序。好的程序,应该是对资源的合理利用,亦或是
用更少的资源(使用合理的算法),实现更多有效的产出。
影响程序的资源一般而言分为4个:CPU、内存、IO、网络。本文着重讲解一下在linux系统下,如何查看高CPU占用率的进程,线程。
2.python代码
为了模拟真实场景,我们用python程序模拟一个高CPU占用的情景,即开大量的线程,线程内部也使用无限循环(空跑),以下为python代码cpu.py:
#-*- coding:utf-8 -*-
import time, threading
#测试线程的个数
num = 500
def loop():
print 'thread %s is running...' % threading.current_thread().name
k = 0
while k < 500:
k += 1
time.sleep(1)
def special():
print 'thread %s is running...' % threading.current_thread().name
while True:
pass
#启动一些普通线程
for i in range(num):
t = threading.Thread(target=loop, name='normal-' + str(i))
t.start()
t = threading.Thread(target=special, name='special')
t.start()
在linux系统中,使用 python cpu.py 运行该程序。
3.问题排查时使用的命令
如何确定高cpu消耗的进程:
方法1 用top简单看一下:
标红的部分,很明显能发现较高的cpu占用情况。
方法2 用ps -eo pid,pcpu | sort -n -k 2 (当然,可以tail一下)
如何确定高cpu消耗的线程:
方法1 用top -H
标红的部分就是高cpu消耗的线程信息。
方法2 用ps H -eo pid,tid,pcpu | sort -n -k 3
假如我知道高cpu消耗的进程号是多少了,查看它的线程信息的方法为:
方法 1: pstree -p pid
方法 2: 查看线程的详细信息:cat /proc/进程号/task/线程号/status
方法 3: 实时显示 top -H -p pid
方法 4: htop,通过htop查看单个进程的线程,然后按<F2>来进入htop的设置菜单。选择“设置”栏下
面的“显示选项”,然后开启“树状视图”和“显示自定义线程名”选项。按<F10>退出设置。
方法 5: 查看该进程下所有的线程 ps -efL | grep pid
注意:
如您发现本文档中有明显错误的地方,
或者您发现本文档中引用了他人的资料而未进行说明时,请联系我进行更正。
转载或使用本文档时,请作醒目说明。
必要时请联系作者,否则将追究相应的法律责任。
note:
If you find this document with any error ,
Or if you find any illegal citations , please contact me correct.
Reprint or use of this document,Please explain for striking.
Please contact the author if necessary, or they will pursue the corresponding legal responsibility.
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!