python中程序运行计时的三种方式

发布时间:2019-09-21 10:59:30编辑:auto阅读(1778)

    下面这段程序截取自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)
    1. 在command line中使用Unix内置的 time 命令

      先在程序末尾加入:

      if __name__ == '__main__':
      benchmark()

      然后运行:

      $ time python3 simul.py
      python3 simul.py  1.16s user 0.02s system 97% cpu 1.221 total
    2. 使用 timeit module

      You can specify the number of loops or repetitions with the options -n and -r (https://docs.python.org/2/library/timeit.html).

      1. IPyhton Shell或者Ipython Notebook中使用magic commands:
        %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,现在感觉是不好的习惯。

      2. 在Command Line中使用

        $ python3 -m timeit -s 'from simul import benchmark' 'benchmark()'
      3. 在程序中加入计时函数

        import timeit
        def timing():
            result = timeit.timeit('benchmark()', setup=
            'from __main__ import benchmark', number=10)
            print(result)
            # Result is the time it takes to run the whole loop
            result = timeit.repeat('benchmark()', setup=
            'from __main__ import benchmark', number=10,
                           repeat=3)
            print(result)
            # Result is a list of times
        
        if __name__ == '__main__':
            timing()

关键字