How to time python

(*-*)浩
(*-*)浩Original
2019-06-29 14:08:015489browse

Timing is a critical part of understanding the performance of your program. This article discusses timing methods in Python 2 and Python 3.

How to time python

Common timing method for python2 and python3 (Recommended learning: Python video tutorial)

Because of python2 It is different from the timing function in 3. It is recommended to use timeit.default_timer() in the timeit module

According to the official documentation of timeit.default_timer(), the timing accuracy is related to the platform and the function used:

"Defined in the default timer, in different ways for different platforms. On Windows, time.clock() has microsecond precision, but time.time() precision is 1/60s .On Unix, time.clock() has 1/100s accuracy, and time.time() is far more accurate. On other platforms, default_timer() measures wall clock time, not CPU time. This Means that other processes on the same computer may affect timing."

In python2:

if sys.platform == "win32":
    # On Windows, the best timer is time.clock()
    default_timer = time.clock
else:
    # On most other platforms the best timer is time.time()
    default_timer = time.time

In python3:

default_timer = time.perf_counter

It can be seen from the official documentation of time.clock():

"time.clock() is obsolete after python3.3 version: the behavior of this function is affected by the platform, use time.perf_counter()" Or time.process_time() instead to get a better defined behavior, depending on your needs. ”

For more Python-related technical articles, please visit the Python Tutorial column to learn!

The above is the detailed content of How to time python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How python runs codeNext article:How python runs code