PyCharm 提供了一个名为 timeit
的内置模块,可以用来计算 Python 代码的执行时间。使用 timeit
模块,您可以在 PyCharm 中轻松比较两段代码的执行时间。
以下是一个示例代码,演示了如何使用 timeit
模块计算两段代码的执行时间:
import timeit
# 第一段代码
def code_1():
# ...
# 第二段代码
def code_2():
# ...
# 执行第一段代码并计算执行时间
time_1 = timeit.timeit(code_1, number=1000)
# 执行第二段代码并计算执行时间
time_2 = timeit.timeit(code_2, number=1000)
# 对比两段代码的执行时间
if time_1 < time_2:
print('第一段代码执行更快')
else:
print('第二段代码执行更快')
在上面的示例中,我们首先定义了两个函数,分别代表了两段代码。然后,我们使用 timeit.timeit()
函数来执行这两个函数并计算它们的执行时间。最后,我们比较这两个执行时间以确定哪个代码执行得更快。
请注意,timeit.timeit()
函数的 number
参数定义了每个函数执行的次数。在上面的示例中,我们将 number
参数设置为 1000,这意味着每个函数都将被执行 1000 次。
可以根据需要调整这个数字来获得更准确的执行时间。
或者我们有一个更简便的方式取调试函数的耗时问题,
首先编写io监控和打印的函数
@contextlib.contextmanager
def profiled():
# 性能测试
pr = cProfile.Profile()
pr.enable()
yield
pr.disable()
s = io.StringIO()
ps = pstats.Stats(pr, stream=s).sort_stats('cumulative')
ps.print_stats()
# uncomment this to see who's calling what
# ps.print_callers()
run_log = s.getvalue()
# 定义列名的映射关系
column_mapping = {
'ncalls': '调用次数',
'tottime': '函数耗时',
'percall': '平均耗时',
'cumtime': '总+子函数耗时',
'filename:lineno(function)': '文件名:行号(函数名)'
}
# 替换列名为中文
for eng_col, chi_col in column_mapping.items():
run_log = run_log.replace(eng_col, chi_col)
# 打印输出
print(run_log)
然后再需要监控的函数前加入with
语句
with profiled:
my_function()
这样当my_function()
执行完毕时就会打印里面的子函数的耗时和io