python中函数的准确计时 [英] Accurate timing of functions in python

查看:32
本文介绍了python中函数的准确计时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Windows 上用 python 编程,想准确测量函数运行所需的时间.我编写了一个函数time_it",它接受另一个函数,运行它,并返回运行所需的时间.

I'm programming in python on windows and would like to accurately measure the time it takes for a function to run. I have written a function "time_it" that takes another function, runs it, and returns the time it took to run.

def time_it(f, *args):
    start = time.clock()
    f(*args)
    return (time.clock() - start)*1000

我调用了 1000 次并取平均值.(最后的 1000 常数是以毫秒为单位给出答案.)

i call this 1000 times and average the result. (the 1000 constant at the end is to give the answer in milliseconds.)

这个函数似乎可以工作,但我总觉得我做错了什么,而且通过这样做,我使用的时间比函数在运行时实际使用的时间要多.

This function seems to work but i have this nagging feeling that I'm doing something wrong, and that by doing it this way I'm using more time than the function actually uses when its running.

是否有更标准或更可接受的方法来做到这一点?

Is there a more standard or accepted way to do this?

当我更改测试函数以调用打印以使其花费更长的时间时,我的 time_it 函数返回平均 2.5 毫秒,而 cProfile.run('f()') 返回平均 7.0 毫秒.我想我的函数会高估时间,如果有的话,这里发生了什么?

When i changed my test function to call a print so that it takes longer, my time_it function returns an average of 2.5 ms while the cProfile.run('f()') returns and average of 7.0 ms. I figured my function would overestimate the time if anything, what is going on here?

另外要注意的是,我关心的是函数之间的相对时间,而不是绝对时间,因为这显然会因硬件和其他因素而异.

One additional note, it is the relative time of functions compared to each other that i care about, not the absolute time as this will obviously vary depending on hardware and other factors.

推荐答案

与其编写自己的分析代码,我建议您查看内置的 Python 分析器(profilecProfile,取决于您的需要):http://docs.python.org/library/profile.html

Instead of writing your own profiling code, I suggest you check out the built-in Python profilers (profile or cProfile, depending on your needs): http://docs.python.org/library/profile.html

这篇关于python中函数的准确计时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆