Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Get timer ticks in Python

I'm just trying to time a piece of code. The pseudocode looks like:

start = get_ticks()
do_long_code()
print "It took " + (get_ticks() - start) + " seconds."

How does this look in Python?

More specifically, how do I get the number of ticks since midnight (or however Python organizes that timing)?

question from:https://stackoverflow.com/questions/156330/get-timer-ticks-in-python

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

1 Reply

0 votes
by (71.8m points)

In the time module, there are two timing functions: time and clock. time gives you "wall" time, if this is what you care about.

However, the python docs say that clock should be used for benchmarking. Note that clock behaves different in separate systems:

  • on MS Windows, it uses the Win32 function QueryPerformanceCounter(), with "resolution typically better than a microsecond". It has no special meaning, it's just a number (it starts counting the first time you call clock in your process).
    # ms windows
    t0= time.clock()
    do_something()
    t= time.clock() - t0 # t is wall seconds elapsed (floating point)
  • on *nix, clock reports CPU time. Now, this is different, and most probably the value you want, since your program hardly ever is the only process requesting CPU time (even if you have no other processes, the kernel uses CPU time now and then). So, this number, which typically is smaller1 than the wall time (i.e. time.time() - t0), is more meaningful when benchmarking code:
    # linux
    t0= time.clock()
    do_something()
    t= time.clock() - t0 # t is CPU seconds elapsed (floating point)

Apart from all that, the timeit module has the Timer class that is supposed to use what's best for benchmarking from the available functionality.

1 unless threading gets in the way…

2 Python ≥3.3: there are time.perf_counter() and time.process_time(). perf_counter is being used by the timeit module.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...