Skip to content

Commit

Permalink
trtop: Fix CPU usage issues
Browse files Browse the repository at this point in the history
Signed-off-by: iipeace <[email protected]>
  • Loading branch information
iipeace committed Oct 6, 2023
1 parent 81d94bb commit 25fe409
Showing 1 changed file with 137 additions and 63 deletions.
200 changes: 137 additions & 63 deletions guider/guider.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
__credits__ = "Peace Lee"
__license__ = "GPLv2"
__version__ = "3.9.8"
__revision__ = "231005"
__revision__ = "231006"
__maintainer__ = "Peace Lee"
__email__ = "[email protected]"
__repository__ = "https://github.com/iipeace/guider"
Expand Down Expand Up @@ -7098,7 +7098,14 @@ def getStdev(data):
def _variance(data, ddof=0):
n = len(data)
mean = sum(data) / n
return __builtins__.sum((x - mean) ** 2 for x in data) / (n - ddof)
v = n - ddof
diffs = [(x - mean) ** 2 for x in data]
try:
return __builtins__.sum(diffs) / v
except SystemExit:
sys.exit(0)
except:
return sum(diffs) / v

var = _variance(data)
math = SysMgr.getPkg("math")
Expand Down Expand Up @@ -28174,11 +28181,13 @@ def _readPipe(wbuf, pipeInput):
_printPage(wbuf, cursor)

def _handleInput(key, cursor, wbuf, lastWord):
# set cmd #
if key:
k = key[0]
else:
k = ""

# handle cmd #
if k == "q":
sys.exit(0)
elif k == "f":
Expand All @@ -28193,7 +28202,7 @@ def _handleInput(key, cursor, wbuf, lastWord):
cursor -= 1
elif k in ("\x1b[C", "", "k"):
cursor += 1
elif k == "p":
elif k == "l":
sys.stdout.write(
"< last line: %s >" % UtilMgr.convNum(len(wbuf))
)
Expand Down Expand Up @@ -36868,16 +36877,17 @@ def _getDesc(s, t=0):
-v verbose

Keys:
f Move to Next Page
b Move to Prev Page
g Move to First Page
G Move to Last Page
k Move to Next Line
j Move to Prev Line
/ Search Line
n Search Next Line
N Search Prev Line
p Print Last Line
f Move to next page
b Move to prev page
g Move to first page
G Move to last page
k Move to next line
j Move to prev line
NUM Move to the line
/ Search line
n Search next line
N Search prev line
l Print last line
q Quit
"""

Expand Down Expand Up @@ -45430,7 +45440,7 @@ def writeTraceCmd(path, val, append=False):
os.close(fd)
except:
pass
else:
elif val:
fd.write(val)
try:
fd.close()
Expand Down Expand Up @@ -47098,12 +47108,14 @@ def printPipe(line="", newline=True, flush=False, pager=True, trim=True):
# internal less #
if SysMgr.isLinux and "LESS" in SysMgr.environList:
# run less as pager #
ecmd = os.path.join(
SysMgr.getExeName(SysMgr.pid), SysMgr.getPyPath()
ecmd = "%s %s %s" % (
SysMgr.getExeName(SysMgr.pid),
SysMgr.getPyPath(),
"less",
)
ecmd += " less"
SysMgr.pipeForPager = os.popen(ecmd, "w")
SysMgr.setPipeSize(SysMgr.pipeForPager)
SysMgr.ttyRows = SysMgr.ttyCols = sys.maxsize
# external less #
elif UtilMgr.which("less"):
# defopt = '-FRSXMQi'
Expand Down Expand Up @@ -65278,6 +65290,23 @@ def doPstree(targets, title=True, printFunc=None, canRepeat=False):
if maxLine and not stream:
SysMgr.clearScreen()

# save timestamp #
prevTime = time.time()

# oneshot #
if not canRepeat or not SysMgr.intervalEnable:
TaskAnalyzer.printProcTree(
obj,
title=title,
printFunc=printFunc,
targets=targets,
maxLine=maxLine,
)
break

if not obj.prevCpuData:
SysMgr.printEnable = False

TaskAnalyzer.printProcTree(
obj,
title=title,
Expand All @@ -65286,10 +65315,23 @@ def doPstree(targets, title=True, printFunc=None, canRepeat=False):
maxLine=maxLine,
)

if not canRepeat or not SysMgr.intervalEnable:
break
if not obj.prevCpuData:
SysMgr.printEnable = True

time.sleep(SysMgr.intervalEnable)
# check repeat count #
SysMgr.checkProgress()

# reset system status #
obj.reinitStats()

# get delayed time #
delayTime = time.time() - prevTime
if delayTime > SysMgr.intervalEnable:
waitTime = 0.000001
else:
waitTime = SysMgr.intervalEnable - delayTime

time.sleep(waitTime)

@staticmethod
def doMerge():
Expand Down Expand Up @@ -68396,8 +68438,7 @@ def enableEvents():
SysMgr.applyTraceAttr(filters, "enable", "1", True)

# prepare for recovering tracing status after printing #
tracingStat = SysMgr.readTraceFile("../tracing_on")
orig = SysMgr.readFile(tracingStat)
orig = SysMgr.readTraceFile("../tracing_on")
SysMgr.addExitFunc(SysMgr.writeTraceCmd, ["../tracing_on", orig])

# write command to start tracing #
Expand Down Expand Up @@ -107293,9 +107334,13 @@ def drawYticks(ax, ymax, fontsize=0, adjust=True, unit=10, ymin=-1):

# adjust ticks #
if adjust:
ymin = long(ymin)
ymax = long(ymax)

inc = long(ymax / unit)
if inc == 0:
inc = 1

yticks(xrange(ymin, long(ymax + inc), inc), fontsize=fontsize)
else:
yticks(fontsize=fontsize)
Expand Down Expand Up @@ -107323,9 +107368,13 @@ def drawYticks(ax, ymax, fontsize=0, adjust=True, unit=10, ymin=-1):

# adjust yticks #
if adjust:
ymin = long(ymin)
ymax = long(ymax)

inc = long(ymax / unit)
if inc == 0:
inc = 1

yticks(xrange(ymin, long(ymax + inc), inc), fontsize=fontsize)
else:
yticks(fontsize=fontsize)
Expand Down Expand Up @@ -111204,6 +111253,10 @@ def drawViolin(
newXnameList = []
newYnameList = []

# init subNameList #
if not subNameList:
subNameList = [""] * len(posInfo)

# set pos info #
try:
if not posInfo:
Expand All @@ -111224,7 +111277,12 @@ def drawViolin(
[list(statList[idx])],
[nameList[idx]],
]
newSubNameList.append(subNameList[idx])

if idx in subNameList:
newSubNameList.append(subNameList[idx])
else:
raise Exception("no subNameList")

if len(xname) > idx:
newXnameList.append(xname[idx])
if len(yname) > idx:
Expand Down Expand Up @@ -119745,45 +119803,17 @@ def printProcTree(
except:
netinfo = ""

title = "[%s Tree Info]" % target

printUserInfo = "USERINFO" in SysMgr.environList
if printUserInfo:
try:
SysMgr.sysInstance.saveUserInfo()
except SystemExit:
sys.exit(0)
except:
pass

# print title #
printFunc(
("\n%s (Uptime: %s)%s\n%s\n" " %-24s %4s(%11s/%15s) <%s>\n%s")
% (
title,
UtilMgr.convTime(SysMgr.uptime),
netinfo,
twoLine,
"Name(ID)",
("[Current] " if curCpu else "[Total] ") + "Per",
"CPUTIME",
"RUNTIME",
"SUB",
lastLine,
)
)

# print nodes in tree #
def _printTreeNodes(root, depth, targets, enable, current):
treestr = ""

# check depth #
if SysMgr.funcDepth > 0 and SysMgr.funcDepth <= depth:
return treestr
return "", 0

cpu = 0
treestr = ""
initStatus = enable
convColor = UtilMgr.convColor

initStatus = enable
for pid, children in sorted(
root.items(), key=lambda x: long(x[0])
):
Expand Down Expand Up @@ -119813,7 +119843,7 @@ def _printTreeNodes(root, depth, targets, enable, current):
):
treestr += _printTreeNodes(
children, depth + 1, targets, enable, current
)
)[0]
continue
else:
enable = True
Expand Down Expand Up @@ -119863,13 +119893,13 @@ def _printTreeNodes(root, depth, targets, enable, current):
except SystemExit:
sys.exit(0)
except:
ttime = "?"
ttime = 0
ttimestr = "?"

# get CPU time by runtime #
try:
# ignore tasks used CPU lesser than 1% #
if nostat or ttime < 1:
if nostat or not ttime:
raise Exception()

# calculate current cpu usage #
Expand All @@ -119884,11 +119914,13 @@ def _printTreeNodes(root, depth, targets, enable, current):
if cpuPer <= 0:
raise Exception()

nrCpuPer = cpuPer
cpuPer = "%5.1f" % cpuPer
cpuPer = convColor(cpuPer, "RED", 5)
except SystemExit:
sys.exit(0)
except:
nrCpuPer = 0
cpuPer = "%5s" % 0

# get user info #
Expand All @@ -119911,13 +119943,28 @@ def _printTreeNodes(root, depth, targets, enable, current):
except:
userInfo = ""

# get child nodes #
treestrret, ctime = _printTreeNodes(
children, depth + 1, targets, enable, current
)
if curCpu and (not SysMgr.showAll and not targets):
if not nrCpuPer and not ctime:
continue

cpu += nrCpuPer
cpu += ctime
if not ctime:
treestrret = ""

# init indent string #
if depth == 0:
indent = "\n"

# make indent #
for _ in xrange(depth):
indent = "%s%s|" % (indent, " " * 5)

# get memory stats #
if not nostat and addMem and instanceOrig:
if SysMgr.isRoot():
stats = ["rss", "pss", "uss"]
Expand All @@ -119939,6 +119986,7 @@ def _printTreeNodes(root, depth, targets, enable, current):
else:
memstr = ""

# build stat string #
if nostat:
stats = ""
else:
Expand All @@ -119963,11 +120011,9 @@ def _printTreeNodes(root, depth, targets, enable, current):
treestr = treestr.rstrip() + " <%s>" % nrChild

# add child nodes #
treestr += "\n%s" % _printTreeNodes(
children, depth + 1, targets, enable, current
)
treestr += "\n%s" % treestrret

return treestr
return treestr, cpu

# set initial switch #
if targets:
Expand All @@ -119984,12 +120030,40 @@ def _printTreeNodes(root, depth, targets, enable, current):
current = time.time()

# get string for tree #
finalstr = _printTreeNodes(procTree, 0, targets, enable, current)
finalstr = _printTreeNodes(procTree, 0, targets, enable, current)[0]
if finalstr:
finalstr = "%s\n%s" % (finalstr.strip("\n"), oneLine)
else:
finalstr = " None\n" + oneLine

title = "[%s Tree Info]" % target

printUserInfo = "USERINFO" in SysMgr.environList
if printUserInfo:
try:
SysMgr.sysInstance.saveUserInfo()
except SystemExit:
sys.exit(0)
except:
pass

# print title #
printFunc(
("\n%s (Uptime: %s)%s\n%s\n" " %-24s %4s(%11s/%15s) <%s>\n%s")
% (
title,
UtilMgr.convTime(SysMgr.uptime),
netinfo,
twoLine,
"Name(ID)",
("[Current] " if curCpu else "[Total] ") + "Per",
"CPUTIME",
"RUNTIME",
"SUB",
lastLine,
)
)

# recover color flag #
SysMgr.colorEnable = origColor

Expand Down

0 comments on commit 25fe409

Please sign in to comment.