下面这段程序截取自Python High Performance Programming(个人觉得这本书还不错,虽然有点零碎。因为我做数据分析比较多,有时候数据量大了确实也需要考虑代码优化。当然,如果数据量太大,我应该还是会毫不犹豫地用SAS。)
下面的程序里有一个benchmark函数,现在来用不同方法得出该函数的运行时间。
class Particle:
__slots__ = ('x', 'y', 'ang_speed')
def __init__(self, x, y, ang_speed):
self.x = x
self.y = y
self.ang_speed = ang_speed
class ParticleSimulator:
def __init__(self, particles):
self.particles = particles
def evolve(self, dt):
timestep = 0.00001
nsteps = int(dt/timestep)
for i in range(nsteps):
for p in self.particles:
norm = (p.x**2 + p.y**2)**0.5
v_x = (-p.y)/norm
v_y = p.x/norm
d_x = timestep * p.ang_speed * v_x
d_y = timestep * p.ang_speed * v_y
p.x += d_x
p.y += d_y
from random import uniform
def benchmark():
particles = [Particle(uniform(-1.0, 1.0),
uniform(-1.0, 1.0),
uniform(-1.0, 1.0))
for i in range(100)]
simulator = ParticleSimulator(particles)
simulator.evolve(0.1)
time
命令
先在程序末尾加入:
if __name__ == '__main__': benchmark()
然后运行:
$ time python3 simul.py python3 simul.py 1.16s user 0.02s system 97% cpu 1.221 totaltimeit
module
You can specify the number of loops or repetitions with the options -n and -r (https://docs.python.org/2/library/timeit.html).
%timeit
: for single-line snippets
%%timeit
: for multi-line snippets
In [1]: from simul import benchmark In [2]: %timeit benchmark() 1 loops, best of 3: 991 ms per loop
在Ipython Notebook中,我以前习惯于在一段很大的程序前加上%%timeit
,现在感觉是不好的习惯。