Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from timeit import timeit
- import random
- import string
- random.choice(string.ascii_lowercase)
- VALUES_COUNT = 1000
- values = {}
- def gen_random_str():
- return ''.join(random.choice(string.ascii_letters) for _ in range(random.randint(10, 40)))
- for _ in range(VALUES_COUNT):
- values[gen_random_str()] = 'value'
- existing_key = random.choice(list(values.keys()))
- non_existing_key = gen_random_str()
- while non_existing_key in values:
- non_existing_key = gen_random_str()
- def use_existing():
- return values[existing_key]
- def with_try_exists():
- try:
- return values[existing_key]
- except KeyError:
- pass
- def with_try_not_exists():
- try:
- return values[non_existing_key]
- except KeyError:
- pass
- def with_in_check_exist():
- if existing_key in values:
- return values[existing_key]
- def with_in_check_not_exist():
- if non_existing_key in values:
- return values[non_existing_key]
- def with_get_exists():
- values.get(existing_key)
- def with_get_not_exists():
- values.get(non_existing_key)
- timeit(use_existing)
- timeit(with_try_exists)
- timeit(with_try_not_exists)
- timeit(with_in_check_exist)
- timeit(with_in_check_not_exist)
- timeit(with_get_exists)
- timeit(with_get_not_exists)
- '''
- >>> timeit(use_existing)
- 0.09614359300030628
- >>>
- >>> timeit(with_try_exists)
- 0.10425232600027812
- >>> timeit(with_try_not_exists)
- 0.297110736999457
- >>>
- >>> timeit(with_in_check_exist)
- 0.13227759299843456
- >>> timeit(with_in_check_not_exist)
- 0.10016654199716868
- >>>
- >>> timeit(with_get_exists)
- 0.1631382230007148
- >>> timeit(with_get_not_exists)
- 0.1656956420010829
- >>>
- '''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement