目录
- 1、跳过迭代对象的开头
- 2、避免数据复制
- 3、避免变量中间变量
- 4、循环优化
- 5、使用numba.jit
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()
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
评论(0)