python - 如何在python中测量算法的运行时间

标签 python algorithm

Possible Duplicates:
Accurate timing of functions in python
accurately measure time python function takes

我如何测量和比较我用 python 编写的算法的运行时间。如果可以的话,还请给我一个不错的算法站点/论坛,例如 stackoverflow。

最佳答案

对于小型算法,您可以使用模块 timeit 来自 python 文档:

def test():
    "Stupid test function"
    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()

不太准确但仍然有效,您可以像这样使用模块时间:

from time import time
t0 = time()
call_mifuntion_vers_1()
t1 = time()
call_mifunction_vers_2()
t2 = time()

print 'function vers1 takes %f' %(t1-t0)
print 'function vers2 takes %f' %(t2-t1)

关于python - 如何在python中测量算法的运行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2662140/

相关文章:

python - 如何将 utf-8 字符串显示/转换为正确的符号

python - Hadoop Map中最高/最低温度的python mapreduce示例

python - 为什么要为结构化数据使用递归神经网络?

python - 我可以在代码中的 python 游戏中包含音乐吗?

php - 我是否需要像 PHP 那样使用 Python 编写 Node.js?

Python系列算法

algorithm - 基于多约束算法找到最优值

python - 递归调度算法不能正常工作 Python

algorithm - 多变环境的寻路算法

r - R中大数据的计数算法