2008-10-01 74 views
40

我只是想要計算一段代碼。僞碼看起來像:在Python中獲取計時器刻度

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

這是Python看起來如何?

更具體地說,我如何獲得自午夜以來的滴答數(或Python是否組織這個時間)?

+0

相關:[測量Python在Python中消逝的時間?](http://stackoverflow.com/q/7370801/4279) – jfs 2016-02-28 18:46:09

回答

33

time模塊,有兩個定時功能:timeclocktime給你「牆」的時間,如果這是你所關心的。

但是,python docsclock應該用於基準測試。需要注意的是clock行爲在不同的系統不同:

  • 在MS Windows,它使用Win32函數QueryPerformanceCounter的(),用「通常比一微秒更好的分辨率」。它沒有特別的含義,它只是一個數字(它在你的過程中第一次呼叫clock開始計數)。
 
    # ms windows 
    t0= time.clock() 
    do_something() 
    t= time.clock() - t0 # t is wall seconds elapsed (floating point) 
    在* nix
  • clock報告的CPU時間。現在,這是不同的,最可能的是你想要的價值,因爲你的程序幾乎不是唯一的請求CPU時間的進程(即使你沒有其他進程,內核現在使用CPU時間)。 - 那麼,這個數字,這通常是比牆時間smaller¹基準測試代碼時(即選定了time.time()T0),是更有意義:
 
    # linux 
    t0= time.clock() 
    do_something() 
    t= time.clock() - t0 # t is CPU seconds elapsed (floating point) 
從所有

除此之外,該timeit模塊具有Timer類應該使用什麼最適合從可用功能進行基準測試。

¹除非線程礙事...

²的Python≥3.3:有time.perf_counter() and time.process_time()。 模塊正在使用perf_counter

+0

`time.clock()`在* nix上可能精度較差。 [使用`timeit.default_timer`](http://stackoverflow.com/a/25823885/4279),以獲得最佳計時器,用於測量不同操作系統和Python版本的時間性能。 – jfs 2016-02-28 18:49:09

30

你需要的是從time模塊time()功能:

import time 
start = time.time() 
do_long_code() 
print "it took", time.time() - start, "seconds." 

可以使用timeit模塊更多的選擇,雖然。

2
import datetime 

start = datetime.datetime.now() 
do_long_code() 
finish = datetime.datetime.now() 
delta = finish - start 
print delta.seconds 

從午夜:

import datetime 

midnight = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) 
now = datetime.datetime.now() 
delta = now - midnight 
print delta.seconds 
+0

這不包括在datetime中傳遞的天數(在技術上微秒,但由於我們沒有關心那些......),如果長碼需要比您想象的更長的時間,那麼將會非常不準確。 – leetNightshade 2012-11-09 01:08:01

2

在Python中time module,您可以訪問時鐘()函數,它在幾秒鐘內返回時間爲浮點。

不同的系統根據內部時鐘設置(每秒鐘的滴答時間)會有不同的精確度,但通常至少低於20毫秒,在某些情況下優於幾微秒。

- 亞當

4

下面是我開始使用新的解決方案:

class Timer: 
    def __enter__(self): 
     self.begin = now() 

    def __exit__(self, type, value, traceback): 
     print(format_delta(self.begin, now())) 

你使用這樣的(你至少需要Python 2.5中):

with Timer(): 
    do_long_code() 

當你的代碼完成後,計時器會自動打印出運行時間。甜!如果我想迅速在Python解釋器中進行某些操作,這是最簡單的方法。

下面是'now'和'format_delta'的示例實現,儘管可以隨意使用您的首選時間和格式化方法。

import datetime 

def now(): 
    return datetime.datetime.now() 

# Prints one of the following formats*: 
# 1.58 days 
# 2.98 hours 
# 9.28 minutes # Not actually added yet, oops. 
# 5.60 seconds 
# 790 milliseconds 
# *Except I prefer abbreviated formats, so I print d,h,m,s, or ms. 
def format_delta(start,end): 

    # Time in microseconds 
    one_day = 86400000000 
    one_hour = 3600000000 
    one_second = 1000000 
    one_millisecond = 1000 

    delta = end - start 

    build_time_us = delta.microseconds + delta.seconds * one_second + delta.days * one_day 

    days = 0 
    while build_time_us > one_day: 
     build_time_us -= one_day 
     days += 1 

    if days > 0: 
     time_str = "%.2fd" % (days + build_time_us/float(one_day)) 
    else: 
     hours = 0 
     while build_time_us > one_hour: 
      build_time_us -= one_hour 
      hours += 1 
     if hours > 0: 
      time_str = "%.2fh" % (hours + build_time_us/float(one_hour)) 
     else: 
      seconds = 0 
      while build_time_us > one_second: 
       build_time_us -= one_second 
       seconds += 1 
      if seconds > 0: 
       time_str = "%.2fs" % (seconds + build_time_us/float(one_second)) 
      else: 
       ms = 0 
       while build_time_us > one_millisecond: 
        build_time_us -= one_millisecond 
        ms += 1 
       time_str = "%.2fms" % (ms + build_time_us/float(one_millisecond)) 
    return time_str 

請讓我知道如果你有一個首選的格式化方法,或者是否有做這一切更簡單的方法!

0

如果你想當時許多語句,你可以使用這樣的事情:

class Ticker: 
    def __init__(self): 
     self.t = clock() 

    def __call__(self): 
     dt = clock() - self.t 
     self.t = clock() 
     return 1000 * dt 

那麼你的代碼可能是這樣的:

tick = Ticker() 
# first command 
print('first took {}ms'.format(tick()) 
# second group of commands 
print('second took {}ms'.format(tick()) 
# third group of commands 
print('third took {}ms'.format(tick()) 

這樣,你不需要在每個塊之前輸入t = time(),之後輸入1000 * (time() - t),同時仍然保持對格式化的控制(儘管您也可以很容易地將其放入Ticket)。

這是一個微不足道的收益,但我認爲這很方便。