gpt4 book ai didi

Python:计算给定行执行了多少次

转载 作者:太空狗 更新时间:2023-10-29 21:52:47 24 4
gpt4 key购买 nike

问题

出于教学目的,我想计算给定行在给定函数中执行了多少次而不对其进行修改或修饰。例如,对于函数:

def binary_search(seq, x):
(a, b) = (0, len(seq) - 1)
while a <= b:
m = (a + b) / 2
if x < seq[m]:
b = m - 1
elif x > seq[m]:
a = m + 1
else:
return m

我会这样写:

print count_exec(binary_search, range(100), 44, line_number = 4) 

...甚至像这样:

print count_exec(binary_search(range(100), 44), line = "m = (a + b) / 2")

...两者都应打印第 4 行的执行次数(即 7)。最终目标是为任何函数的复杂性提供一种经验方法:

Complexity of binary search

非解决方案

我目前的解决方案是添加一个函数属性:

def binary_search(seq, x):
binary_search.count = 0 # <------------------ added
(a, b) = (0, len(seq) - 1)
while a <= b:
binary_search.count += 1 # <------------- added
m = (a + b) / 2
if x < seq[m]:
b = m - 1
elif x > seq[m]:
a = m + 1
else:
return m

binary_search(range(100), 44)
print binary_search.count

我想我可以创建一个修饰函数count_this_line:

def binary_search(seq, x):
(a, b) = (0, len(seq) - 1)
while a <= b:
count_this_line() # <-------------------- added
m = (a + b) / 2
...

也许可以装饰函数 binary_search 本身,但对我来说这算作修改它。

想法

  • 标准库 ast可以检索任何给定脚本的抽象语法树,甚至可以执行它。
  • 我在使用 Python 分析器方面经验不足。对于我的需要来说,它似乎很笨重。这可能是要走的路吗?

最佳答案

您可以使用 line_profiler 模块来执行此操作 (see docs)。请注意,我必须从 forked repo 获得 3.x 兼容版本。 - 不确定它是否已合并。

例如。我把你的二进制搜索函数放在一个文件中,然后添加了这个:

prof = profile(binary_search)
prof(range(100), 44)

这与文档中提到的 @profile 装饰器相同,但您不必修改原始 代码。我跑了

kernprof.py -l binsearch.py
python -m line_profiler binsearch.py.lprof

弹出这个:

Function: binary_search at line 1
Total time: 4.1e-05 s

Line # Hits Time Per Hit % Time Line Contents
==============================================================
1 def binary_search(seq, x):
2 1 6 6.0 14.6 (a, b) = (0, len(seq) - 1)
3 7 8 1.1 19.5 while a <= b:
4 7 7 1.0 17.1 m = (a + b) // 2
5 7 8 1.1 19.5 if x < seq[m]:
6 2 2 1.0 4.9 b = m - 1
7 5 5 1.0 12.2 elif x > seq[m]:
8 4 4 1.0 9.8 a = m + 1
9 else:
10 1 1 1.0 2.4 return m

“点击数”是您要查找的数字。作为奖励,您还可以获得时间信息,尽管对于许多执行来说这会更准确。

关于Python:计算给定行执行了多少次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25287294/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com