【问题标题】:Faster to save Division to a Variable and use the variable or Recalculate twice?更快地将除法保存到变量并使用变量或重新计算两次?
【发布时间】:2019-01-06 17:32:45
【问题描述】:

假设您有以下数据类型(作为参数填充的数字):

  • 整数 权重
  • 浮动 高度

目标是计算 body-mass index 看起来像 23.13 等...

bodyMassIndex = 体重/身高^2

我想使用 bmi 更像是例如将 bmi (float) 转换为 int 或将 bmi 除以模数等...

是先保存bmi再在其他计算中使用变量(选项a)还是在其他计算中再次进行公式计算(选项b)在计算速度方面更快(选项b)?


选项 A:

**bmi** = weight / height^2

OtherCalculation = **bmi** % 10

...

选项 B:

bmi = weight / (height^2)

OtherCalculation = (weight / height^2) % 10

OtherOtherCalculation =  (weight / height^2) * 100

...

编辑:我正在用 Python 编写

【问题讨论】:

  • 你用什么语言工作?
  • 我正在使用 Python

标签: python performance optimization computation-theory


【解决方案1】:

我决定使用 python 的 timeit 模块对您的示例进行基准测试。我选择了任意高度和宽度,因为这些值不会影响比较结果。使用下面的脚本,我发现(不出所料)将值保存到中间变量的速度至少是 Python 3.x 和 Python 2.x 的两倍。

from timeit import timeit

runs = 1000000

option_a = "(w / h ** 2)"
option_b = "bmi"

setup_a = "w = 4.1; h = 7.6"
setup_b = "{}; bmi = {}".format(setup_a, option_a)

test_1 = "v = {} % 10"
test_2 = "v = {} * 100"


print(timeit(test_1.format(option_a), setup=setup_a, number=runs))
print(timeit(test_1.format(option_b), setup=setup_b, number=runs))

print(timeit(test_2.format(option_a), setup=setup_a, number=runs))
print(timeit(test_2.format(option_b), setup=setup_b, number=runs))

Python 3 中的结果

0.2930161730000691
0.082850623000013
0.17264470200007054
0.06962196800031961

在 Python 2 中

0.126236915588
0.0508558750153
0.113535165787
0.0394539833069

【讨论】:

    猜你喜欢
    • 2011-06-12
    • 2019-11-19
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2019-07-04
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    相关资源
    最近更新 更多