talkpython / async-techniques-python-course

Async Techniques and Examples in Python Course
https://training.talkpython.fm/courses/explore_async_python/async-in-python-with-threading-and-multiprocessing
MIT License
451 stars 249 forks source link

Why threads were faster than not threads in threads calculation example #15

Closed immunochomik closed 3 years ago

immunochomik commented 3 years ago

This might be a wired way of reaching out but, I have checked why the threaded example for 05-threads/cpu_attempt/compute_threaded.py is ~15% faster than non threaded one. Basically the threaded version does computation on floats because of the devisions you make, whereas synchronous example uses ints. So apparently the floats computations are a bit faster than integer ones.

mikeckennedy commented 3 years ago

Hi @immunochomik

I'm not so sure it's that clean-cut but thanks for pointing out that I somehow didn't do exactly the same math (which was the intention, just wanted to compute differently but same math).

Have a look at this:

>>> def run(num_type, times):
...     t0 = datetime.datetime.now()
...     for _ in range(0, times):
...         n = num_type(_)
...         z = n * 100
...     dt = datetime.datetime.now() - t0
...     print(f"Ran in {dt.total_seconds()/1000} ms")

Running for int is just ever so slightly faster than float

Screen Shot 2020-11-11 at 10 18 33 PM
immunochomik commented 3 years ago

In this example running with ints is faster because in the case of floats you are spending time covering ints produced by range to the floats. (I am a big fan by the way)