Created
March 20, 2015 03:43
-
-
Save kocsenc/2febe8fafd36454b9d11 to your computer and use it in GitHub Desktop.
Sleep Sort with ThreadPool
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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