Search code examples
pythonperformanceoptimizationcomputation-theory

Faster to save Division to a Variable and use the variable or Recalculate twice?


Imagine you have the following datatypes (numbers being filled as arguments):

  • Integer <- Weight
  • Float <- Height

The goal is to calculate the body-mass index which will look like 23.13 etc...

bodyMassIndex = weight / height^2

I want to work with the bmi a bit more like for example convert the bmi (float) to int or divide the bmi by modulu etc...

Is it faster in terms of computational speed to save the bmi first and then use the variable in other calculations (option a) or do the formula calculation in the other calculation again (option b) ?


Option A:

**bmi** = weight / height^2

OtherCalculation = **bmi** % 10

...

Option B:

bmi = weight / (height^2)

OtherCalculation = (weight / height^2) % 10

OtherOtherCalculation =  (weight / height^2) * 100

...

Edit: I'm writting in Python


Solution

  • I decided to benchmark your examples using python's timeit module. I chose an arbitrary height and width since those values will not affect the results of the comparison. Using the script below, I found that (unsurprisingly) saving the values to an intermediate variable is at least twice as fast for both Python 3.x and 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))
    

    The results in Python 3

    0.2930161730000691
    0.082850623000013
    0.17264470200007054
    0.06962196800031961
    

    And in Python 2

    0.126236915588
    0.0508558750153
    0.113535165787
    0.0394539833069