How do you determine a processing time in Python?

2020-02-09 06:09发布

I'm new to Python, and confused by the date/time documentation. I want to compute the time that it takes to perform a computation.

In java, I would write:

long timeBefore = System.currentTimeMillis();
doStuff();
long timeAfter = System.currentTimeMillis();
elapsed time = timeAfter - timeBefore;

I'm sure it's even easier in Python. Can anyone help?

9条回答
爷、活的狠高调
2楼-- · 2020-02-09 06:15
python -m timeit -h
查看更多
We Are One
3楼-- · 2020-02-09 06:15

If all you want is the time between two points in code (and it seems that's what you want) I have written tic() toc() functions ala Matlab's implementation. The basic use case is:

tic()

''' some code that runs for an interesting amount of time '''

toc()

# OUTPUT:
# Elapsed time is: 32.42123 seconds

Super, incredibly easy to use, a sort of fire-and-forget kind of code. It's available on Github's Gist https://gist.github.com/tyleha/5174230

查看更多
4楼-- · 2020-02-09 06:22

Equivalent in python would be:

>>> import time
>>> tic = time.clock()
>>> toc = time.clock()
>>> toc - tic

If you are trying to find the best performing method then you should probably have a look at timeit.

查看更多
叛逆
5楼-- · 2020-02-09 06:23

For Python 3.3 and later time.process_time() is very nice:

import time

t = time.process_time()
#do some stuff
elapsed_time = time.process_time() - t
查看更多
迷人小祖宗
6楼-- · 2020-02-09 06:25

Building on and updating a number of earlier responses (thanks: SilentGhost, nosklo, Ramkumar) a simple portable timer would use timeit's default_timer():

>>> import timeit
>>> tic=timeit.default_timer()
>>> # Do Stuff
>>> toc=timeit.default_timer()
>>> toc - tic #elapsed time in seconds

This will return the elapsed wall clock (real) time, not CPU time. And as described in the timeit documentation chooses the most precise available real-world timer depending on the platform.

ALso, beginning with Python 3.3 this same functionality is available with the time.perf_counter performance counter. Under 3.3+ timeit.default_timer() refers to this new counter.

For more precise/complex performance calculations, timeit includes more sophisticated calls for automatically timing small code snippets including averaging run time over a defined set of repetitions.

查看更多
▲ chillily
7楼-- · 2020-02-09 06:29

You can implement two tic() and tac() functions, where tic() captures the time which it is called, and tac() prints the time difference since tic() was called. Here is a short implementation:

import time

_start_time = time.time()

def tic():
    global _start_time 
    _start_time = time.time()

def tac():
    t_sec = round(time.time() - _start_time)
    (t_min, t_sec) = divmod(t_sec,60)
    (t_hour,t_min) = divmod(t_min,60) 
    print('Time passed: {}hour:{}min:{}sec'.format(t_hour,t_min,t_sec))

Now in your code you can use it as:

tic()
do_some_stuff()
tac()

and it will, for example, output:

Time passed: 0hour:7min:26sec

See also:

查看更多
登录 后发表回答