您好,我遇到了一个问题,即我的脚本中的一个函数需要很长时间才能执行。所以我正在尝试优化代码,我目前正在为此使用 cProfile 和 Pstats。
当我执行一个函数时,大约需要 0.7 秒到 1+ 秒才能完成。在 Windows 上总是给出最长持续时间的项目是:
Sun Mar 10 13:55:02 2019 profiles/getColors.profile
657 function calls in 0.535 seconds
Ordered by: internal time
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.714 0.714 0.714 0.714 {built-in method _winapi.WaitForMultipleObjects}_winapi.WaitForMultipleObjects}
在 Linux 上:
2 1.013 0.506 1.013 0.506 {built-in method posix.read}
所以我会假设它必须对线程做一些事情,但我从不创建任何线程,而我的其他函数几乎不需要时间来完成,比如 ~0.1 秒,所以我的问题是为什么要花这么长时间来执行这段代码:
def getColors(image, rows, columns, sectionedPixel):
# Flooring so we do not get decimal numbers
sectionColumns = math.floor(width / columns)
sectionRows = math.floor(height / rows)
colorValues = [0, 0, 0, 0]
leftRGBVal = [0, 0, 0]
rightRGBVal = [0, 0, 0]
topRGBVal = [0, 0, 0]
botRGBVal = [0, 0, 0]
# LEFT SIDE
getRiLeSideColor(image, 0, 10, leftRGBVal)
# RIGHT SIDE
getRiLeSideColor(image, width - 10, width, rightRGBVal)
# TOP SIDE
getToBoSideColor(image, 0, 10, topRGBVal)
# BOTTOM SIDE
getToBoSideColor(image, height - 10, height, botRGBVal)
colorValues[0] = leftRGBVal
colorValues[1] = rightRGBVal
colorValues[2] = topRGBVal
colorValues[3] = botRGBVal
return colorValues
CProfile 的完整日志: https ://pastebin.com/jAA5FkPZ
完整代码: https ://gist.github.com/Patrick265/592a7dccba4660a4e4210ddd5e9974eb