How long does my Python application take to run?

2019-02-03 03:41发布

Basically, I want to be able to output the elapsed time that the application is running for. I think I need to use some sort of timeit function but I'm not sure which one. I'm looking for something like the following...

START MY TIMER
code for application
more code
more code
etc
STOP MY TIMER

OUTPUT ELAPSED TIME to do the above code in between start and stop of timer. Thoughts?

标签: python timer
5条回答
Deceive 欺骗
2楼-- · 2019-02-03 03:47

The simplest way to do it is to put:

import time
start_time = time.time()

at the start and

print "My program took", time.time() - start_time, "to run"

at the end.

查看更多
Melony?
3楼-- · 2019-02-03 03:49

You could use the system command time:

foo@foo:~# time python test.py
hello world!

real    0m0.015s
user    0m0.008s
sys     0m0.007s
查看更多
贼婆χ
4楼-- · 2019-02-03 03:51

Couldn't you just get the current system time at the start and at the end, then subtract the start time from the final time?

查看更多
我只想做你的唯一
5楼-- · 2019-02-03 03:55

To get the best result on different platforms:

from timeit import default_timer as timer

# START MY TIMER
start = timer()
code for application
more code
more code
etc
# STOP MY TIMER
elapsed_time = timer() - start # in seconds

timer() is a time.perf_counter() in Python 3.3 and time.clock()/time.time() in older versions on Windows/other platforms correspondingly.

查看更多
做个烂人
6楼-- · 2019-02-03 04:06

If you're running Mac OS X or Linux, just use the time utility:

$ time python script.py
real    0m0.043s
user    0m0.027s
sys     0m0.013s

If not, use the time module:

import time

start_time = time.time()

# ...

print time.time() - start_time, 's'
查看更多
登录 后发表回答