如何在Python中测量经过时间? [英] How to measure elapsed time in Python?

查看:145
本文介绍了如何在Python中测量经过时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要的是开始在代码中的某个地方开始计时,然后获取经过的时间,以测量执行少量功能所花费的时间.我认为我使用的timeit模块错误,但是文档对我来说却很混乱.

What I want is to start counting time somewhere in my code and then get the passed time, to measure the time it took to execute few function. I think I'm using the timeit module wrong, but the docs are just confusing for me.

import timeit

start = timeit.timeit()
print("hello")
end = timeit.timeit()
print(end - start)

推荐答案

如果只想测量两点之间经过的挂钟时间,则可以使用

If you just want to measure the elapsed wall-clock time between two points, you could use time.time():

import time

start = time.time()
print("hello")
end = time.time()
print(end - start)

这以秒为单位给出执行时间.

This gives the execution time in seconds.

自3.3版本以来的另一种选择是使用 perf_counter process_time ,具体取决于您的要求.在3.3之前,建议使用 time.clock (感谢琥珀).但是,目前不推荐使用:

Another option since 3.3 might be to use perf_counter or process_time, depending on your requirements. Before 3.3 it was recommended to use time.clock (thanks Amber). However, it is currently deprecated:

在Unix上,以浮点数返回当前处理器时间 以秒表示.精度,实际上就是定义 处理器时间"的含义取决于C函数的含义 同名.

On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of "processor time", depends on that of the C function of the same name.

在Windows上,此函数返回自 第一次调用此函数,作为一个浮点数,基于 Win32函数QueryPerformanceCounter().分辨率通常是 优于一微秒.

On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond.

版本3.3起已弃用:此功能的行为取决于 在平台上:改为使用perf_counter()process_time() , 根据您的要求,具有明确的行为.

Deprecated since version 3.3: The behaviour of this function depends on the platform: use perf_counter() or process_time() instead, depending on your requirements, to have a well defined behaviour.

这篇关于如何在Python中测量经过时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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