看啥推荐读物
专栏名称: Python开发者
人生苦短,我用 Python。伯乐在线旗下账号「Python开发者」分享 Python 相关的技术文章、工具资源、精选课程、热点资讯等。
今天看啥  ›  专栏  ›  Python开发者

加速 Python for 循环

Python开发者  · 公众号  · Python  · 2024-05-17 08:48
来源:deephub在本文中,我将介绍一些简单的方法,可以将Python for循环的速度提高1.3到900倍。Python内建的一个常用功能是timeit模块。下面几节中我们将使用它来度量循环的当前性能和改进后的性能。对于每种方法,我们通过运行测试来建立基线,该测试包括在10次测试运行中运行被测函数100K次(循环),然后计算每个循环的平均时间(以纳秒为单位,ns)。几个简单方法1、列表推导式 # Baseline version (Inefficient way) # Calculating the power of numbers # Without using List Comprehension def test_01_v0(numbers):   output = []   for n in numbers:       output.append(n ** 2.5)   return output  # Improved version # (Using List Comprehension) def test_01_v1(numbers):   output = [n ** 2.5 for n in numbers]   return output结果如下: # Summary Of Test Results      Baseline: 32.158 ns per loop ………………………………

原文地址:访问原文地址
快照地址: 访问文章快照