1. Learn
  2. /
  3. Курси
  4. /
  5. 高效编写 Python 代码

Connected

вправа

使用 %lprun:修复瓶颈

在上一个练习中,您对 convert_units() 函数进行了分析,发现 new_hts 的列表推导可能是一个性能瓶颈。您是否也注意到,new_wts 的列表推导占用的运行时间百分比相近?这表明,您也许应该用另一种方法来创建 new_hts 和 new_wts 对象。

由于每位英雄的身高和体重都存储在 numpy 数组中,您可以使用数组广播来替代列表推导进行单位转换。下面的函数已经实现了这一点:

def convert_units_broadcast(heroes, heights, weights):

    # Array broadcasting instead of list comprehension
    new_hts = heights * 0.39370
    new_wts = weights * 2.20462

    hero_data = {}

    for i,hero in enumerate(heroes):
        hero_data[hero] = (new_hts[i], new_wts[i])

    return hero_data

请在您的 IPython 会话中加载 line_profiler 包。然后使用 %lprun 对作用于超级英雄数据的 convert_units_broadcast() 函数进行分析。convert_units_broadcast() 函数、heroes 列表、hts 数组和 wts 数组已加载到您的会话中。完成代码后,请回答以下问题:

在 convert_units_broadcast() 函数的总执行时间中,new_hts 数组广播这一行代码占用的时间百分比是多少?

Інструкції

50 XP

Можливі відповіді