前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python中程序运行计时的三种方式

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

作者头像
py3study
发布2020-01-06 15:13:24
3.3K0
发布2020-01-06 15:13:24
举报
文章被收录于专栏:python3python3

下面这段程序截取自Python High Performance Programming(个人觉得这本书还不错,虽然有点零碎。因为我做数据分析比较多,有时候数据量大了确实也需要考虑代码优化。当然,如果数据量太大,我应该还是会毫不犹豫地用SAS。)

下面的程序里有一个benchmark函数,现在来用不同方法得出该函数的运行时间。

代码语言:javascript
复制
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()
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档