#测试一段代码
#知识点1:定义两个函数 分别是立方和平方,分别取看他们的运算结果
#定义函数 一个放回0-n的平方 一个返回0-n的立方
#1.创建 列表 然后append数据再返回
def square(n):
data = []
for x in range(0,n):
data.append(x**2)
return data
def cube(n):
data = []
for x in range(0, n):
data.append(x ** 3)
return data
def square1(n):
return [i ** 2 for i in range(0,n+1)]
def cube1(n):
return [i ** 3 for i in range(0, n+1)]
#验证效率 使用时间
import time
#验证运行时间
time1 = time.time()
square(200000)
cube(200000)
time2 = time.time()
print(f"运行时间是{time2-time1}")
time1 = time.time()
square1(200000)
cube1(200000)
time2 = time.time()
print(f"推导式的方式运行时间是{time2-time1}")
#两个数组中各个元素相加
pingfang = square1(200000)
lifang = cube1(200000)
time1 = time.time()
data = []
for x in range(0,len(pingfang)):
data.append(pingfang[x]+lifang[x])
time2 = time.time()
print(time2-time1)
newdata = [pingfang[i]+lifang[i] for i in range(0,len(pingfang))]
time2 = time.time()
print(time2-time1)
python效率验证
最新推荐文章于 2024-05-29 13:52:09 发布