217:スクリプトの処理時間を計測する
Rubyだとスクリプトや子プロセスの処理時間を調べる関数があるようだ。 pythonだと2.3から実装されたtimeitモジュール が相当するらしい。でも使い方がよく分からない。
そこで単純に実行前と実行後の時間差を取る事にする。今の時間はtimeモジュールのtime()関数でエポック(多分1900年)からの秒数で取り出せる。精度は多分ない。バックグランドの影響なども受けてしまう。
import time
start=time.time()
for x in range(100000):
x=x*x
stop=time.time()
diff=stop-start
print diff
5.77800011635
http://pleac.sourceforge.net/pleac_python/datesandtimes.html
#----------------------------- # High Resolution Timers t1 = time.clock() # Do Stuff Here t2 = time.clock() print t2 - t1 # 2.27236813618 # Accuracy will depend on platform and OS, # but time.clock() uses the most accurate timer it can time.clock(); time.clock() # 174485.51365466841 # 174485.55702610247 #----------------------------- # Also useful; import timeit code = '[x for x in range(10) if x % 2 == 0]' eval(code) # [0, 2, 4, 6, 8] t = timeit.Timer(code) print "10,000 repeats of that code takes:", t.timeit(10000), "seconds" print "1,000,000 repeats of that code takes:", t.timeit(), "seconds" # 10,000 repeats of that code takes: 0.128238644856 seconds # 1,000,000 repeats of that code takes: 12.5396490336 seconds #----------------------------- import timeit code = 'import random; l = random.sample(xrange(10000000), 1000); l.sort()' t = timeit.Timer(code) print "Create a list of a thousand random numbers. Sort the list. Repeated a thousand times." print "Average Time:", t.timeit(1000) / 1000 # Time taken: 5.24391507859