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

深藏阁楼爱情的钟 2022-01-05 07:49 501阅读 0赞

1 程序实现对比

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

  1. # 测试函数式编程所用时间
  2. import timeit, math
  3. import matplotlib.pyplot as plt
  4. from pylab import mpl
  5. mpl.rcParams['font.sans-serif'] = ['FangSong'] # 设置matplotlib可以显示汉语
  6. mpl.rcParams['axes.unicode_minus'] = False
  7. mpl.rcParams['font.size'] = 13
  8. y1, y2, y3 = [], [], []
  9. x = [i for i in range(1000, 100000, 1000)]
  10. for num in range(1000, 100000, 1000):
  11. original = [i for i in range(num)]
  12. t1 = timeit.default_timer()
  13. res1 = []
  14. for eve in original:
  15. res1.append(1 / ((math.exp(-eve)) + 1))
  16. t2 = timeit.default_timer()
  17. y1.append(t2-t1)
  18. t3 = timeit.default_timer()
  19. # print("\n", "正常循环所用时间:{}".format(t2-t1), "\n", "------------------------------------------------------------------------------")
  20. res2 = [1 / ((math.exp(-eve)) + 1) for eve in original]
  21. t4 = timeit.default_timer()
  22. y2.append(t4-t3)
  23. t5 = timeit.default_timer()
  24. # print("\n", "列表推导式时间:{}".format(t3-t2), "\n", "------------------------------------------------------------------------------")
  25. res3 = list(map(lambda x: 1/((math.exp(-x))+1), original))
  26. t6 = timeit.default_timer()
  27. y3.append(t6-t5)
  28. # print("\n", "map函数式编程时间:{}".format(t4-t3), "\n", "------------------------------------------------------------------------------")
  29. print(y1)
  30. print(y2)
  31. print(y3)
  32. plt.figure(1)
  33. plt.plot(x, y1, label="正常循环所用时间")
  34. plt.plot(x, y2, label="列表推导式时间")
  35. plt.plot(x, y3, label="map函数式编程时间")
  36. plt.xlabel("循环次数")
  37. plt.ylabel("所用时间(秒)")
  38. plt.legend()
  39. plt.show()

2 实验对比结果

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

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzQ4MzM4MQ_size_16_color_FFFFFF_t_70

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzQ4MzM4MQ_size_16_color_FFFFFF_t_70 1

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzQ4MzM4MQ_size_16_color_FFFFFF_t_70 2

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

发表评论

表情:
评论列表 (有 0 条评论,501人围观)

还没有评论,来说两句吧...

相关阅读