开始使用免费开始使用

计时测量 I

在幻灯片中,您已经看到如何加载并使用 time.time() 函数来评估执行一个基础数学运算所需的时间。

现在,您将用同样的策略来评估两种解决相似问题的方法:计算从 1 到 100 万(1,000,000)所有正整数的平方和。

与视频中类似,您将比较两种方法:一种是"蛮力"遍历,另一种是更"数学化"的方法。

formula 函数中,我们使用标准公式:

$$ \frac{N*(N+1)(2N+1)}{6} $$

其中 N=1,000,000。

brute_force 函数中,我们对 1 到 100 万的每个数字进行循环,并将其平方累加到结果中。

本练习是课程的一部分

使用 pandas 编写高效代码

查看课程

练习说明

  • 使用 formula() 函数计算该问题的结果。
  • 打印使用 formula() 函数计算结果所需的时间。
  • 使用 brute_force() 函数计算该问题的结果。
  • 打印使用 brute_force() 函数计算结果所需的时间。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Calculate the result of the problem using formula() and print the time required
N = 1000000
fm_start_time = ____
first_method = formula(N)
print("Time using formula: {} sec".format(time.time() - fm_start_time))

# Calculate the result of the problem using brute_force() and print the time required
sm_start_time = ____
second_method = ____(N)
print("Time using the brute force: {} sec".format(time.time() - sm_start_time))
编辑并运行代码