Skip to content

Instantly share code, notes, and snippets.

@jarshwah
Created November 17, 2015 02:40
Show Gist options
  • Save jarshwah/f28d84987aadc7bcb2f5 to your computer and use it in GitHub Desktop.
Save jarshwah/f28d84987aadc7bcb2f5 to your computer and use it in GitHub Desktop.
Timing python moving if outside loop
smeatonj ~/Development
$ python3 -m timeit -s 'from testif import without_if' 'without_if(0, 100)'
100000 loops, best of 3: 4.94 usec per loop
smeatonj ~/Development
$ python3 -m timeit -s 'from testif import with_if' 'with_if(0, 100)'
100000 loops, best of 3: 5.88 usec per loop
smeatonj ~/Development
$ python3 -m timeit -s 'from testif import without_if' 'without_if(0, 10000)'
1000 loops, best of 3: 590 usec per loop
smeatonj ~/Development
$ python3 -m timeit -s 'from testif import with_if' 'with_if(0, 10000)'
1000 loops, best of 3: 698 usec per loop
smeatonj ~/Development
$ python3 -m timeit -s 'from testif import without_if' 'without_if(5, 10000)'
1000 loops, best of 3: 1.36 msec per loop
smeatonj ~/Development
$ python3 -m timeit -s 'from testif import with_if' 'with_if(5, 10000)'
1000 loops, best of 3: 1.46 msec per loop
def without_if(converter_count, range_count):
converters = get_converters(converter_count)
count = 0
if converters:
for x in range(range_count):
count = count + converters[0]
count = count + x
else:
for x in range(range_count):
count = count + x
return count
def with_if(converter_count, range_count):
converters = get_converters(converter_count)
count = 0
for x in range(range_count):
if converters:
count = count + converters[0]
count = count + x
return count
def get_converters(num):
if num < 1:
return []
return [1] * num
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment