分享5个python提速技巧,速度瞬间提上来了
程序员文章站
2022-06-23 19:32:20
目录1、跳过迭代对象的开头2、避免数据复制3、避免变量中间变量4、循环优化5、使用numba.jit1、跳过迭代对象的开头string_from_file = """ // wooden: ......
1、跳过迭代对象的开头
string_from_file = """ // wooden: ... // laoli: ... // // whole: ... wooden laoli... """ import itertools for line in itertools.dropwhile(lambda line: line.startswith("//"), string_from_file.split(" ")): print(line)
2、避免数据复制
# 不推荐写法,代码耗时:6.5秒 def main(): size = 10000 for _ in range(size): value = range(size) value_list = [x for x in value] square_list = [x * x for x in value_list] main()
# 推荐写法,代码耗时:4.8秒 def main(): size = 10000 for _ in range(size): value = range(size) square_list = [x * x for x in value] # 避免无意义的复制
3、避免变量中间变量
# 不推荐写法,代码耗时:0.07秒 def main(): size = 1000000 for _ in range(size): a = 3 b = 5 temp = a a = b b = temp main()
# 推荐写法,代码耗时:0.06秒 def main(): size = 1000000 for _ in range(size): a = 3 b = 5 a, b = b, a # 不借助中间变量 main()
4、循环优化
# 不推荐写法。代码耗时:6.7秒 def computesum(size: int) -> int: sum_ = 0 i = 0 while i < size: sum_ += i i += 1 return sum_ def main(): size = 10000 for _ in range(size): sum_ = computesum(size) main()
# 推荐写法。代码耗时:4.3秒 def computesum(size: int) -> int: sum_ = 0 for i in range(size): # for 循环代替 while 循环 sum_ += i return sum_ def main(): size = 10000 for _ in range(size): sum_ = computesum(size) main()
隐式for循环代替显式for循环
# 推荐写法。代码耗时:1.7秒 def computesum(size: int) -> int: return sum(range(size)) # 隐式 for 循环代替显式 for 循环 def main(): size = 10000 for _ in range(size): sum = computesum(size) main()
5、使用numba.jit
# 推荐写法。代码耗时:0.62秒 # numba可以将 python 函数 jit 编译为机器码执行,大大提高代码运行速度。 import numba @numba.jit def computesum(size: float) -> int: sum = 0 for i in range(size): sum += i return sum def main(): size = 10000 for _ in range(size): sum = computesum(size) main()
到此这篇关于分享5个python提速技巧,速度瞬间提上来了的文章就介绍到这了,更多相关python提速技巧内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
上一篇: APP第5篇 APP分类和手机选择
下一篇: 详解Java设计模式中的装饰模式