python怎么加快函数运行速度

870
2021/2/13 14:58:28
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

python怎么加快函数运行速度

在python中加快函数运行速度的方法有以下几种

1.使用内置函数,去掉属性访问

from math import sqrt # 直接引用特定函数或属性

import time

def func():

lst = []

for i in range(1, 10000000):

lst.append(sqrt(i)) # 直接调用 sqrt

return lst

start = time.time()

lst = func()

end = time.time()

print(end-start)

2.使用函数生成器

from math import sqrt

import time

def func():

# for 循环改为列表推导式

lst = [sqrt(i) for i in range(1, 10000000)]

return lst

start = time.time()

lst = func()

end = time.time()

print(end-start)

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: ubuntu中怎么指定python版本