Python 官方文档:入门教程 => 点击学习
下面这段程序截取自python High PerfORMance Programming(个人觉得这本书还不错,虽然有点零碎。因为我做数据分析比较多,有时候数据量大了确实也需要考虑代码优化。当然,如果数据量太大,我应该还是会毫不犹
下面这段程序截取自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)
在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
使用 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).
在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
,现在感觉是不好的习惯。
在Command Line中使用
$ python3 -m timeit -s 'from simul import benchmark' 'benchmark()'
在程序中加入计时函数
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()
--结束END--
本文标题: python中程序运行计时的三种方式
本文链接: https://www.lsjlt.com/news/191273.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0