So the situation is: “repeating a block of code n times”.
These are the timings of different approaches.
Code
from itertools import repeat, cycle, count, islice
R_NONE = repeat(None)
def test0(n):
for _ in islice(R_NONE, n):
pass
def test1(n):
for _ in repeat(None, n):
pass
def test2(n):
for _ in range(n):
pass
def test3(n):
i = 0
while i < n:
i += 1
def test4(n):
while n:
n -= 1
def test5(n):
ct = count()
while next(ct) < n:
pass
ns = [1, 5, 10, 50, 100, 1000]
map = {
'irepeat': test0,
'repeat': test1,
'range': test2,
'while': test3,
'while-': test4,
'count': test5,
}
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ 5 repeats, 1,000 times ┃
┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
┃ Units: ns 1 5 10 50 100 1000 ┃
┃ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
┃ irepeat ┃ 216 248 301 659 1,139 9,553 ┃
┃ repeat ┃ 214 239 273 541 876 7,054 ┃
┃ range ┃ 192 225 236 518 856 21,247 ┃
┃ while ┃ 74 148 260 1,025 2,064 35,814 ┃
┃ while- ┃ 76 135 232 903 1,741 31,311 ┃
┃ count ┃ 274 415 566 1,855 3,594 49,131 ┃
┗━━━━━━━━━━━┻━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
The problem is:
- There doesn’t seem to be one best method to do this
- For
n <= 10, usewhile - For
10 < n <= 100, usefor _ in range - For
100 < n, usefor _ in itertools.repeat(None, n)
The question is:
- Could there be one without introducing new compound statement?

