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提速技巧内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!