python 普通循环、列表推导式、map()函数三者效率的对比

1 程序实现对比

分别使用普通循环、列表推导式、map()函数三种方法来计算1/(exp(-x)+1)的值,来比较它们的效率差异。

# 测试函数式编程所用时间
import timeit, math
import matplotlib.pyplot as plt
from pylab import mpl

mpl.rcParams['font.sans-serif'] = ['FangSong']  # 设置matplotlib可以显示汉语
mpl.rcParams['axes.unicode_minus'] = False
mpl.rcParams['font.size'] = 13


y1, y2, y3 = [], [], []
x = [i for i in range(1000, 100000, 1000)]
for num in range(1000, 100000, 1000):
    original = [i for i in range(num)]


    t1 = timeit.default_timer()
    res1 = []
    for eve in original:
        res1.append(1 / ((math.exp(-eve)) + 1))
    t2 = timeit.default_timer()

    y1.append(t2-t1)

    t3 = timeit.default_timer()
    # print("\n", "正常循环所用时间:{}".format(t2-t1), "\n", "------------------------------------------------------------------------------")
    res2 = [1 / ((math.exp(-eve)) + 1) for eve in original]
    t4 = timeit.default_timer()

    y2.append(t4-t3)

    t5 = timeit.default_timer()
    # print("\n", "列表推导式时间:{}".format(t3-t2), "\n", "------------------------------------------------------------------------------")
    res3 = list(map(lambda  x: 1/((math.exp(-x))+1), original))
    t6 = timeit.default_timer()

    y3.append(t6-t5)

    # print("\n", "map函数式编程时间:{}".format(t4-t3), "\n", "------------------------------------------------------------------------------")

print(y1)
print(y2)
print(y3)

plt.figure(1)
plt.plot(x, y1, label="正常循环所用时间")
plt.plot(x, y2, label="列表推导式时间")
plt.plot(x, y3, label="map函数式编程时间")
plt.xlabel("循环次数")
plt.ylabel("所用时间(秒)")
plt.legend()
plt.show()

2 实验对比结果

为了更好的比较三种结构的运行效率,进行了三次对比试验,如下图所示:

可以发现在小规模循环运算的过程中三者并没有明显的效率区别,但是总体来说,列表推导式的效率最高,其次是map()函数,正常的for循环效率是最低的,这一点尤其在解决大循环量问题时较为明显。

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值