下面的两个函数都执行相同的基本操作集获取整数的二进制repr,去掉前2个字符,用零填充,然后从右边执行一个切片。你知道吗
但是,loop1的运行时间是loop2的两倍。如果能深入了解为什么会这样,我们将不胜感激。你知道吗
def loop1(wires):
pad = '0'*wires
def _trim(m, sl):
return m[sl:]
def _pad(m):
return pad+m
for n in xrange(2**wires - 1):
m = bin(n)
m = _trim(m, 2)
m = _pad(m)
m = _trim(m, -4)
def loop2(wires):
pad = '0'*wires
for n in xrange(2**wires - 1):
m = bin(n)
m = (pad+m[2:])[-4:]
cProfile.run('loop1(24)')
cProfile.run('loop2(24)')
67108863 function calls in 22.005 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 11.669 11.669 22.005 22.005 <module1>:78(loop1)
33554430 3.834 0.000 3.834 0.000 <module1>:82(_trim)
16777215 1.992 0.000 1.992 0.000 <module1>:84(_pad)
1 0.000 0.000 22.005 22.005 <string>:1(<module>)
16777215 4.510 0.000 4.510 0.000 {bin}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
16777218 function calls in 9.482 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 5.160 5.160 9.482 9.482 <module1>:96(loop2)
1 0.000 0.000 9.482 9.482 <string>:1(<module>)
16777215 4.322 0.000 4.322 0.000 {bin}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
所谓的
tottime
是自我时间,而所谓的cumtime
是包容时间。你知道吗把
tottime
列加起来,得到大约46,这是_run_inner_loop
的cumtime
。你知道吗注意
_run_inner_loop
花费了大量的自我时间,超过24小时。 我怀疑这是在for
语句中花费的(因为这就是全部内容)。你知道吗如果你试着this,你可以把它钉牢。你知道吗
相关问题 更多 >
编程相关推荐