时间:2022-08-08 08:22:04 | 栏目:Python代码 | 点击:次
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)
# 不推荐写法,代码耗时: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] # 避免无意义的复制
# 不推荐写法,代码耗时: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()
# 不推荐写法。代码耗时: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()
# 推荐写法。代码耗时: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()