-
Notifications
You must be signed in to change notification settings - Fork 284
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Use for comprehension to speed up python code #191
base: main
Are you sure you want to change the base?
Conversation
Thanks! Can you (or someone) provide a deeper explanation of this change? |
Maybe it would be helpful to see a literal C translation of the given Python algorithm? (...or maybe not at all) The operational change is this: And breaking it down from inner-most scope outwards...
And
Finally,
I will say that it appears Python recomputes Altogether, the literal C translation might look like this:
|
Python optimises list comprehensions compared to for loops, here is a video that describes this https://www.youtube.com/watch?v=U88M8YbAzQk Using the Your code:
which is
and the list comprehension that has the same output
which is
with the call to inner loop
The extra optimisation makes the comprehension about twice as fast. Most python practitionners know this optimisation pretty well so will prefer to write comprehensions whenever possible. Obviously it's still a long way away from C/Rust 😅 |
Thank you @mmurrian and @poudro for those wonderful explanations! I'll add my bit. A python list comprehension of the form: my_list = [item for item in other_list] has the same effect as my_list = []
for item in other_list:
my_list.append(item) So starting from the inner list: [j % u for j in range(100_000)] has the same effect as my_list = []
for j in range(100_000):
my_list.append(j % u) Taking the sum of this list is therefore the same as: val = 0
for j in range(100_000):
val += j % u Which is the same as the inner loop in the original code, where a = [sum([j % u for j in range(100_000)]) + r for _ in range(10_000)] As explained by @poudro, most python practitioners are well versed in the fact list comprehensions are faster than python for loops, and so will use these whenever possible. In this case, it leads to less code (only 1 line!) and faster performance. |
d43c8a6
to
b87ec4e
Compare
It's fun seeing how much this looks like the (un-needlessly obfuscated) Haskell implementation. |
You can use |
Hi,
I noticed your python could use with some simple improvements to speed up execution time. For loops in python are slow, but for comprehensions help out a lot. On my machine, this implementation speed things up by about 2x.