Skip to content

Instantly share code, notes, and snippets.

@Nikasa1889
Last active July 26, 2020 03:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nikasa1889/51201768d2c5682948dc1fc29f8f9373 to your computer and use it in GitHub Desktop.
Save Nikasa1889/51201768d2c5682948dc1fc29f8f9373 to your computer and use it in GitHub Desktop.
Test performance of python's bisect and best data struture to work with it
import timeit
setup='''
import random, bisect
from collections import deque
random.seed('slartibartfast')
s = [random.random() for i in range(1000)]
timsort = sorted
def bisect_list(seq):
for i in range(1, len(seq)):
bisect.insort(seq, seq.pop(i), 0, i)
def bisect_deque(seq):
ans = deque([])
for x in seq:
pos = bisect.bisect_left(ans, x)
ans.insert(pos, x)
return ans
'''
# run 1000 times, repeat 7 times, get the best
print("Timsort-List {}".format(min(timeit.Timer('a=s[:]; timsort(a)', setup=setup).repeat(7, 1000)))) # 0.117
print("Timsort-Deque {}".format(min(timeit.Timer('a=deque(s[:]); timsort(a)', setup=setup).repeat(7, 1000)))) # 0.124
print("Bisect-List {}".format(min(timeit.Timer('a=s[:]; bisect_list(a)', setup=setup).repeat(7, 1000)))) # 0.64109
print("Bisect-Deque {}".format(min(timeit.Timer('a=deque(s[:]); bisect_deque(a)', setup=setup).repeat(7, 1000)))) # 0.63
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment