import time
word = {"success":0, "desire":0, "effort":0, ...}
def cleaner(x):
dust = ",./<>?;''[]{}\=+_)(*&^%$#@!`~"
for letter in x:
if letter in dust:
x = x[0:x.index(letter)]+x[x.index(letter)+1:]
else:
pass
return x #alhamdlillah it worked 31.07.12
print "input text to analyze"
itext = cleaner(raw_input()).split()
t = time.clock()
for iword in itext:
if iword in word:
word[iword] += 1
else:
pass
print t
print len(itext)
每次调用代码时,t都会增加。任何人都可以解释这背后的基本概念/原因。也许在系统过程方面?非常感谢,编程小伙伴。
答案 0 :(得分:10)
因为您每次运行脚本时都会打印当前时间
这就是时间的作用,它不断前进。
答案 1 :(得分:3)
如果您想衡量for
循环所花费的时间(在第一次调用time.clock()
和结束之间),请按时间打印差异:< / p>
print time.clock() - t
答案 2 :(得分:0)
您正在打印当前时间...当然,每次运行代码时它都会增加。
来自time.clock()
的python文档:
在Unix上,将当前处理器时间作为浮点数返回 用秒表示。精度,实际上是非常的定义 “处理器时间”的含义取决于C函数的含义 同名,但无论如何,这是用于的功能 基准测试Python或计时算法。
在Windows上,此函数返回自...以来经过的挂号秒 首先调用此函数,作为浮点数,基于 Win32函数QueryPerformanceCounter()。通常是分辨率 好于一微秒。
答案 3 :(得分:0)
time.clock()
返回自创建进程以来经过的 CPU时间。 CPU时间取决于CPU在进程上下文中花费的周期数。它是一个过程生命周期内的单调函数,即如果你在同一个执行中多次调用time.clock()
,你将得到一个增加数字的列表。 clock()
的两次连续调用之间的差异可能小于弹出的挂钟时间或更长时间,具体取决于CPU未运行100%(例如,有一些等待I / O)或者如果你有一个多线程程序,消耗超过100%的CPU时间(例如多核CPU,2个线程,每个75% - >你得到150%的挂钟时间)。但是如果你在一个进程中调用clock()
,那么再次重新运行程序,如果在新进程中处理输入所需的时间较少,则可能会获得比之前更低的值。
你应该做的是使用time.time()
,它以小数(亚秒)精度返回当前的Unix时间戳。您应该在处理开始之前调用一次,然后再调用一次并减去这两个值,以计算两次调用之间经过的挂钟时间。
请注意,在Windows time.clock()
上会返回自启动进程以来经过的挂钟时间。这就像在脚本开头立即调用time.time()
,然后从以后调用time.time()
中减去该值。
答案 4 :(得分:0)
有一个名为jackedCodeTimerPy的非常好的库比时间模块更好。它还有一些聪明的错误检查,所以你可能想尝试一下。
使用jackedCodeTimerPy你的代码应如下所示:
# import time
from jackedCodeTimerPY import JackedTiming
JTimer = JackedTiming()
word = {"success":0, "desire":0, "effort":0}
def cleaner(x):
dust = ",./<>?;''[]{}\=+_)(*&^%$#@!`~"
for letter in x:
if letter in dust:
x = x[0:x.index(letter)]+x[x.index(letter)+1:]
else:
pass
return x #alhamdlillah it worked 31.07.12
print "input text to analyze"
itext = cleaner(raw_input()).split()
# t = time.clock()
JTimer.start('timer_1')
for iword in itext:
if iword in word:
word[iword] += 1
else:
pass
# print t
JTimer.stop('timer_1')
print JTimer.report()
print len(itext)
它提供了非常好的报告,如
label min max mean total run count
------- ----------- ----------- ----------- ----------- -----------
imports 0.00283813 0.00283813 0.00283813 0.00283813 1
loop 5.96046e-06 1.50204e-05 6.71864e-06 0.000335932 50
我喜欢它如何为您提供有关它的统计信息以及计时器运行的次数。
使用简单。如果我想测量for循环中的时间代码,我只需执行以下操作:
from jackedCodeTimerPY import JackedTiming
JTimer = JackedTiming()
for i in range(50):
JTimer.start('loop') # 'loop' is the name of the timer
doSomethingHere = 'This is really useful!'
JTimer.stop('loop')
print(JTimer.report()) # prints the timing report
您也可以同时运行多个计时器。
JTimer.start('first timer')
JTimer.start('second timer')
do_something = 'amazing'
JTimer.stop('first timer')
do_something = 'else'
JTimer.stop('second timer')
print(JTimer.report()) # prints the timing report
回购中有更多使用示例。希望这会有所帮助。