mirror of
https://github.com/autistic-symposium/web3-starter-py.git
synced 2025-05-18 14:40:25 -04:00
add more concurrent examples
This commit is contained in:
parent
6c65e7d226
commit
f35541a061
3 changed files with 104 additions and 0 deletions
47
Concurrence_examples/concurrent_tasks_with_math.py
Normal file
47
Concurrence_examples/concurrent_tasks_with_math.py
Normal file
|
@ -0,0 +1,47 @@
|
|||
import os
|
||||
import time
|
||||
import threading
|
||||
import multiprocessing
|
||||
|
||||
NUM_WORKERS = 4
|
||||
|
||||
def run_numbers():
|
||||
print("PID: %s, Process Name: %s, Thread Name: %s" % (
|
||||
os.getpid(),
|
||||
multiprocessing.current_process().name,
|
||||
threading.current_thread().name)
|
||||
)
|
||||
x = 0
|
||||
while x < 10000000:
|
||||
x += 1
|
||||
|
||||
start_time = time.time()
|
||||
|
||||
for _ in range(NUM_WORKERS):
|
||||
run_numbers()
|
||||
|
||||
end_time = time.time()
|
||||
|
||||
print("Serial time=", end_time - start_time)
|
||||
|
||||
|
||||
start_time = time.time()
|
||||
|
||||
threads = [threading.Thread(target=run_numbers) for _ in range(NUM_WORKERS)]
|
||||
[thread.start() for thread in threads]
|
||||
[thread.join() for thread in threads]
|
||||
|
||||
end_time = time.time()
|
||||
|
||||
print("Threads time=", end_time - start_time)
|
||||
|
||||
|
||||
start_time = time.time()
|
||||
|
||||
processes = [multiprocessing.Process(target=run_numbers) for _ in range(NUM_WORKERS)]
|
||||
[process.start() for process in processes]
|
||||
[process.join() for process in processes]
|
||||
end_time = time.time()
|
||||
|
||||
|
||||
print("Parallel time=", end_time - start_time)
|
Loading…
Add table
Add a link
Reference in a new issue