Search code examples
pythonmultithreadingconcurrent.futures

Python concurrent.futures performance difference with little change


i got the following code:

from concurrent.futures import ThreadPoolExecutor, wait
import datetime

def calculate_mass(mass):
    for _ in range(10000):
        gravity = 9.8
        weight = mass * gravity


def perform_calculations():
    with ThreadPoolExecutor(3) as pool:
        pool.map(calculate_mass, range(1000))

if __name__ == '__main__':
    start = datetime.datetime.now()
    perform_calculations()
    end = datetime.datetime.now()

    print((end - start).total_seconds())

it takes 1.6467 seconds to execute on a core i7 3th generation with 8gb ram (dell notebook)

if change the this line

weight = mass * gravity

to

return mass * gravity

all of a sudden it takes 0.059083 seconds to complete.

Does anyone knows why that happens?

edit: I guess i'm getting tired. i didnt notice the loop was ending. my bad guys


Solution

  • With the line:

    for _ in range(10000):
        gravity = 9.8
        weight = mass * gravity
    

    It is iterating through the for loop 10,000 times. Which will take time.

    However when you change it to:

    for _ in range(10000):
        gravity = 9.8
        return mass * gravity
    

    It is instead returning the value of mass * gravity after only 1 iteration through the for loop.