Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

python - 测量在Python中经过的时间(Measure time elapsed in Python)

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.

(我认为我使用的timeit模块错误,但是文档对我来说却很混乱。)

import timeit

start = timeit.timeit()
print("hello")
end = timeit.timeit()
print(end - start)
  ask by gilbert8 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

import time

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

This gives the execution time in seconds.

(这给出了执行时间(以秒为单位)。)

Another option since 3.3 might be to use perf_counter or process_time , depending on your requirements.

(自3.3起,另一个选择可能是使用perf_counterprocess_time ,具体取决于您的要求。)

Before 3.3 it was recommended to use time.clock (thanks Amber ).

(在3.3之前,建议使用time.clock (感谢Amber )。)

However, it is currently deprecated:

(但是,目前不推荐使用:)

On Unix, return the current processor time as a floating point number expressed in seconds.

(在Unix上,以秒为单位返回当前处理器时间,以浮点数表示。)

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.

(精度,实际上是“处理器时间”含义的确切定义,取决于同名C函数的精度。)

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() .

(在Windows上,此函数基于Win32函数QueryPerformanceCounter()返回自第一次调用此函数以来经过的时间(以秒为单位)的浮点数。)

The resolution is typically better than one microsecond.

(分辨率通常优于一微秒。)

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.

(从版本3.3开始不推荐使用 :此功能的行为取决于平台:根据您的要求, 使用perf_counter()process_time()来具有明确定义的行为。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...