Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Sleep Sort with ThreadPool
from concurrent.futures import ThreadPoolExecutor
import time
import timeit
import random
def sleepsort(lst):
"""
Use ThreadPool to execute each thread. Have it sleep for val/100 and then
add itself to results array.
"""
result = []
def sleep(num, min_val):
real_sleep = (num - min_val) / 100
time.sleep(real_sleep)
result.append(num)
min_val = 0
max_val = 0
for elm in lst:
if elm < min_val:
min_val = elm
if elm > max_val:
max_val = elm
with ThreadPoolExecutor(max_workers = len(lst)) as executor:
for elm in lst:
executor.submit(sleep, elm, min_val)
return result
def generate_random(n, max_range):
"""
Generates a list of random integers from range 0 to maxrange
"""
result = []
for i in range(n):
result.append(random.randrange(1, max_range))
return result
if __name__ == '__main__':
lst = generate_random(100, 3)
sleep_time = timeit.timeit(lambda: sleepsort(lst), number=100)
print("sleep took: " + str(sleep_time))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment