dharmik

@dharmik@linuxusers.in

admin @ linuxusers.in. โ€ข
student. mostly computers.
matrix@spiderham:matrix.org
codeshithttps://github.com/dhrm1k
bloghttps://dhrm1k.github.io

61 following 21 followers

1 ★ 1 ↺
Tech Cyborg boosted

dharmik ยป
@dharmik@linuxusers.in

so i did a few tests to compare a for loop and a generator in python for performance.

1. first test: sum of squares up to n (n = 10^6)
results:

using for-loop:
time taken: 0.271047 seconds
memory used (result): 32 bytes

using generator:
time taken: 0.278367 seconds
memory used (result): n/a

the generator was slightly slower than the for-loop, which was surprising, since i expected the generator to be faster.

2. increased complexity test:
next, i made the test more complex by adding conditional logic (square even numbers, double odd ones) and using dictionaries instead of lists. the results were something like:

Using for-loop:
Time taken: 0.998669 seconds
Memory used (result): 32 bytes

Using generator:
Time taken: 0.990227 seconds
Memory used (result): N/A

yes, now the generator was faster, though slightly. it appears the change is only there when the dataset is bigger.

...

Jonathan Hartley ยป
@tartley@mastodon.social

@dharmik For an eye-opening deep dive on comparing generators which I have for many years recommended to *everyone* learning Python, see David Beazley's classic talk "Generator Tricks for Systems Programmers". The slides linked here stand completely alone. speakerdeck.com/dabeaz/generat

...
1 ★ 0 ↺

dharmik ยป
@dharmik@linuxusers.in

oohh, going through it right now.

History