关于Python花费时间的问题

发布于 2024-09-07 18:07:18 字数 55 浏览 0 评论 0原文

我想知道某个特定函数在涉及递归的程序期间花费了多少时间,最好的方法是什么?

谢谢

I would like to know that how much time a particular function has spent during the duration of the program which involves recursion, what is the best way of doing it?

Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

唠甜嗑 2024-09-14 18:07:18

最好的方法是运行一些 基准测试(测试各个函数)或分析(测试整个应用程序/程序)。 Python 带有内置的分析器。

或者,您可以通过简单地将开始时间设置为程序开始时,并在程序结束时,从开始时间中减去当前时间。这基本上是非常简单的基准测试。

以下是链接问题的答案的实现:

import time
start = time.time()
do_long_code()
print "it took", time.time() - start, "seconds."

Python其标准库中还包含用于基准测试的内容

从页面上给出的示例来看:

def test():
    "Time me"
    L = []
    for i in range(100):
        L.append(i)

if __name__=='__main__':
    from timeit import Timer
    t = Timer("test()", "from __main__ import test")
    print t.timeit()

The best way would be to run some benchmark tests (to test individual functions) or Profiling (to test an entire application/program). Python comes with built-in Profilers.

Alternatively, you could go back to the very basics by simply setting a start time at the beginning of the program, and, at the end of the program, subtracting the current time from the start time. This is basically very simple Benchmarking.

Here is an implementation from the an answer from the linked question:

import time
start = time.time()
do_long_code()
print "it took", time.time() - start, "seconds."

Python has something for benchmarking included in its standard library, as well.

From the example give on the page:

def test():
    "Time me"
    L = []
    for i in range(100):
        L.append(i)

if __name__=='__main__':
    from timeit import Timer
    t = Timer("test()", "from __main__ import test")
    print t.timeit()
厌味 2024-09-14 18:07:18

使用分析器!

python -m cProfile -o prof yourscript.py
runsnake prof

runsnake 是查看分析输出的好工具。您当然可以使用其他工具。

有关探查器的更多信息,请访问:http://docs.python.org/library/profile.html< /a>

Use the profiler!

python -m cProfile -o prof yourscript.py
runsnake prof

runsnake is a nice tool for looking at the profiling output. You can of course use other tools.

More on the Profiler here: http://docs.python.org/library/profile.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文