0

In the following SO question How do I sort a list with positives coming before negatives with values sorted respectively? there were a number of solutions with one of them (well my suggestion) was using numpy arrays... I was thinking it would be fast but it was proven to be the slowest by orders of magnitude, which is fine :), but why is that so? Benchmarks repeated below for convenience:

import numpy as np
from timeit import timeit
from bisect import bisect

def bisectme():
    lst.sort()
    i = bisect(lst, 0)
    return lst[i:] + lst[:i]

def lexicon():
    return sorted(lst, key=lambda x: (x < 0, x))

def comprehension():
    return sorted([i for i in lst if i > 0]) + sorted([i for i in lst if i < 0])

def arrayme():
    return np.concatenate([np.sort(ar[ar >= 0]), np.sort(ar[ar < 0])], axis=0)

lst = list(range(-10**1, 0, 1)) + list(range(10**1, -1, -1))
ar = np.array(lst)


print("bisectme:", timeit(bisectme))
print("lexicon:", timeit(lexicon))
print("comprehension:", timeit(comprehension))
print("arrayme:", timeit(arrayme))

# bisectme: 1.7116674770368263
# lexicon: 8.446330879000016
# comprehension: 5.8491336239967495
# arrayme: 10.91806474502664
Community
  • 1
  • 1
John Smith
  • 1,077
  • 6
  • 21

0 Answers0