Created
November 21, 2018 18:44
-
-
Save SureshKL/b7073e8540487e03e5c57707cf664a56 to your computer and use it in GitHub Desktop.
Python Concurrency
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
import threading | |
import time | |
import random | |
import concurrent.futures | |
numbers = list(range(1, 11)) | |
def product(num): | |
for i in range(1, 10000000): | |
i += num * num | |
return i | |
def threaded(): | |
threads = [] | |
for num in numbers: | |
th = threading.Thread(target=product, args=(num,)) | |
th.start() | |
threads.append(th) | |
for th in threads: | |
th.join() | |
def thread_pool(): | |
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor: | |
for num in numbers: | |
executor.submit(product, num) | |
def process_pool(): | |
with concurrent.futures.ProcessPoolExecutor(max_workers=5) as executor: | |
for num in numbers: | |
executor.submit(product, num) | |
def main(): | |
methods = [threaded, thread_pool, process_pool] | |
for method in methods: | |
start_time = time.time() | |
random.shuffle(numbers) | |
method() | |
end_time = time.time() | |
print(f'Total time by {method.__name__} method {end_time - start_time} secs') | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment