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

查看:42
本文介绍了如何在 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)

推荐答案

如果您只想测量两点之间经过的挂钟时间,您可以使用 time.time():

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_counterprocess_time,取决于您的要求.在 3.3 之前,建议使用 time.clock(感谢 Amber).但是,它目前已被弃用:

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天全站免登陆