Created
June 25, 2011 15:27
-
-
Save bigjason/1046586 to your computer and use it in GitHub Desktop.
Benchmark of get methods with python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import print_function | |
a_dict = {x: str(x) for x in range(1000)} | |
def with_get(): | |
result1 = a_dict.get(-1, None) | |
result2 = a_dict.get(900, None) | |
def with_exception(): | |
try: | |
result1 = a_dict[-1] | |
except KeyError: | |
result1 = None | |
try: | |
result2 = a_dict[900] | |
except KeyError: | |
result2 = None | |
def with_in(): | |
result1 = a_dict[-1] if -1 in a_dict else None | |
result2 = a_dict[900] if 900 in a_dict else None | |
if __name__ == '__main__': | |
import timeit | |
import sys | |
using_get = timeit.Timer('with_get()', 'from __main__ import with_get') | |
using_exception = timeit.Timer('with_exception()', 'from __main__ import with_exception') | |
using_in = timeit.Timer('with_in()', 'from __main__ import with_in') | |
print(sys.version) | |
print() | |
print('with_get(): ', using_get.timeit()) | |
print('with_exception():', using_exception.timeit()) | |
print('with_in(): ', using_in.timeit()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment