Skip to content

Instantly share code, notes, and snippets.

@yuwash
Last active August 1, 2019 06:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuwash/699be7962f280fad2212317d2cdd3766 to your computer and use it in GitHub Desktop.
Save yuwash/699be7962f280fad2212317d2cdd3766 to your computer and use it in GitHub Desktop.
#! /usr/bin/env python
# -*- coding: utf-8 -*-
expect_at = 2**22
plants = expect_at * ['wind'] + ['solar'] + expect_at * ['biogas']
repetitions = 100
def where_is_eafp(target):
try:
return plants.index(target)
except ValueError:
return -1
def where_is_lbyl(target):
if target in plants:
return plants.index(target)
else:
return -1
def where_is_direct(target):
for i, plant in enumerate(plants):
if plant == target:
return i
return -1
if __name__ == '__main__':
where_is = dict(
lbyl=where_is_lbyl,
eafp=where_is_eafp,
direct=where_is_direct,
)['eafp']
for i in range(repetitions):
there = where_is('solar')
print(there)
for i in range(repetitions):
where_is('coal') # doesn’t exist
@yuwash
Copy link
Author

yuwash commented Jul 31, 2019

In my test with expect_at=2**22, repetitions=100 on a dualcore 1.10 GHz laptop the benchmark result was

  • EAFP

    real 0m21.064s
    user 0m20.573s
    sys 0m0.147s

  • LBYL

    real 0m30.577s
    user 0m29.583s
    sys 0m0.196s

  • direct

    real 2m7.483s
    user 2m4.759s
    sys 0m0.205s

By using a larger list than below, this time the result shows a clear superiority of the EAFP implementation as expected.

Unsuccessful search only

When limited to only unsuccessful searches (“coal”), I expected LBYL to be slightly superior as it only does “target in plants” and not “plants.index”, but I was wrong. EAFP was still slightly better (other parameters as above):

  • EAFP

    real 0m14.476s
    user 0m13.940s
    sys 0m0.185s

  • LBYL

    real 0m16.098s
    user 0m15.437s
    sys 0m0.166s

  • direct

    real 1m26.141s
    user 1m24.669s
    sys 0m0.163s

Previous attempt

This first attempt was done with expect_at=100, repetitions=2**22. This was not a very optimal choice so that the result only shows marginal differences.

In my test on a quadcore 2.5 GHz laptop the benchmark result was

  • EAFP

    real 0m14,477s
    user 0m14,395s
    sys 0m0,072s

  • LBYL

    real 0m15,493s
    user 0m15,397s
    sys 0m0,056s

  • direct

    real 0m51,613s
    user 0m51,501s
    sys 0m0,073s

Thus the difference between EAFP and LBYL is minimal, but on repetitive tests EAFP was consistently (slightly) faster. The horrible performance of the “direct” approach is yet another confirmation that you should use library functions (probably implemented in C) instead of writing loops in Python.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment