Skip to content

Commit 2e1e41f

Browse files
feat: range_vs_repeat - itertools.repeat() is faster than range() for looping a fixed number of times when you don't need the loop variable
1 parent 50a1a4d commit 2e1e41f

File tree

6 files changed

+27
-0
lines changed

6 files changed

+27
-0
lines changed

ebook/chapters/third_party_chapters/timing.tex

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,19 @@ \subsection{f-strings VS str}
3939

4040
\textbf{Note:} Even though f-strings are faster in this situation, keep in mind, that the builtin \lstinline{str} function is preferred to be used.
4141
Clean code is usually more important than efficiency.
42+
43+
44+
\subsection{range VS repeat}
45+
46+
\lstinline{itertools.repeat} is faster than \lstinline{range} for looping a fixed number of times when you don't need the loop variable.
47+
An example is given below.
48+
49+
\lstinputlisting[caption=range\_vs\_repeat.py]{../third_party/range_vs_repeat.py}
50+
51+
As you can see, \lstinline{itertools.repeat} is slightly faster.
52+
53+
\begin{lstlisting}[caption=Output of range\_vs\_repeat.py]
54+
$ python range_vs_repeat.py
55+
"Range" spend time: 0.01480103
56+
"Repeat" spend time: 0.01320004
57+
\end{lstlisting}

ebook/python-snippets.epub

333 Bytes
Binary file not shown.

ebook/python-snippets.mobi

618 Bytes
Binary file not shown.

ebook/python-snippets.pdf

1.71 KB
Binary file not shown.

third_party/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ A collection of useful snippets using third party packages.
3333
| parse_complex_excel_sheets | Parse complex Excel Sheets using `pandas` and `xlrd` |
3434
| port_scanner_nmap | Port Scanner using nmap |
3535
| pytest_rename_class_backwards_compatibility | Rename a critical class and test for backwards compatibility |
36+
| range_vs_repeat | `itertools.repeat()` is faster than `range()` for looping a fixed number of times when you don't need the loop variable |
3637
| reduce_pandas_df_memory | Reduce pandas df memory usage by converting `object` to `category` |
3738
| refactoring_code | Refactoring Python code using rope |
3839
| resize_images | Resize all images in the current directory using OpenCV |

third_party/range_vs_repeat.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import itertools
2+
import random
3+
4+
from boxx import timeit
5+
6+
with timeit(name="Range"):
7+
min(random.random() for i in range(100_000))
8+
9+
with timeit(name="Repeat"):
10+
min(random.random() for _ in itertools.repeat(None, 100_000))

0 commit comments

Comments
 (0)