Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from time import time
- import json
- d = {'a': 1, 'b': 2, 'c': 3, 'd': 'aaa', 'e': [1,2,3,4],
- 'f': {'a': 1, 'b': 2, 'c': 3, 'd': 'aaa', 'e': [1,2,3,4], 'f': {}},
- 'g': {'a': 1, 'b': 2, 'c': 3, 'd': 'aaa', 'e': [1,2,3,4], 'f': {}},
- 'h': {'a': 1, 'b': 2, 'c': 3, 'd': 'aaa', 'e': [1,2,3,4], 'f': {}},
- 'i': {'a': 1, 'b': 2, 'c': 3, 'd': 'aaa', 'e': [1,2,3,4], 'f': {}},
- 'j': {'a': 1, 'b': 2, 'c': 3, 'd': 'aaa', 'e': [1,2,3,4], 'f': {'a': 1, 'b': 2, 'c': 3, 'd': 'aaa', 'e': [1,2,3,4],
- 'f': {'a': 1, 'b': 2, 'c': 3, 'd': 'aaa', 'e': [1,2,3,4], 'f': {}},
- 'g': {'a': 1, 'b': 2, 'c': 3, 'd': 'aaa', 'e': [1,2,3,4], 'f': {}},
- 'h': {'a': 1, 'b': 2, 'c': 3, 'd': 'aaa', 'e': [1,2,3,4], 'f': {}},
- 'i': {'a': 1, 'b': 2, 'c': 3, 'd': 'aaa', 'e': [1,2,3,4], 'f': {}},
- 'j': {'a': 1, 'b': 2, 'c': 3, 'd': 'aaa', 'e': [1,2,3,4], 'f': {}},
- }},
- }
- import copy
- def make_hash(o):
- """
- Makes a hash from a dictionary, list, tuple or set to any level, that contains
- only other hashable types (including any lists, tuples, sets, and
- dictionaries).
- """
- if isinstance(o, (set, tuple, list)):
- return tuple([make_hash(e) for e in o])
- elif not isinstance(o, dict):
- return hash(o)
- new_o = copy.deepcopy(o)
- for k, v in new_o.items():
- new_o[k] = make_hash(v)
- return hash(tuple(frozenset(sorted(new_o.items()))))
- N_REP = 10000
- t = time()
- for i in range(N_REP):
- hash(json.dumps(d, sort_keys=True))
- t = time() - t
- print(f"JSON: {t:.02f}s")
- t = time()
- for i in range(N_REP):
- make_hash(d)
- t = time() - t
- print(f"make_hash: {t:.02f}s")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement