mirror of
https://github.com/autistic-symposium/web3-starter-py.git
synced 2025-05-18 06:30:23 -04:00
add concurrent example
This commit is contained in:
parent
e0a6c92e75
commit
6c65e7d226
1 changed files with 49 additions and 0 deletions
49
Concurrence_examples/concurrent_tasks.py
Normal file
49
Concurrence_examples/concurrent_tasks.py
Normal file
|
@ -0,0 +1,49 @@
|
|||
import os
|
||||
import time
|
||||
import threading
|
||||
import multiprocessing
|
||||
|
||||
NUM_WORKERS = 4
|
||||
|
||||
def run_sleep():
|
||||
print("PID: %s, Process Name: %s, Thread Name: %s" % (
|
||||
os.getpid(),
|
||||
multiprocessing.current_process().name,
|
||||
threading.current_thread().name)
|
||||
)
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
# Run tasks serially
|
||||
start_time = time.time()
|
||||
|
||||
for _ in range(NUM_WORKERS):
|
||||
run_sleep()
|
||||
|
||||
end_time = time.time()
|
||||
|
||||
print("Serial time=", end_time - start_time)
|
||||
|
||||
|
||||
# Run tasks using threads
|
||||
start_time = time.time()
|
||||
|
||||
threads = [threading.Thread(target=run_sleep) 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)
|
||||
|
||||
|
||||
# Run tasks using processes
|
||||
start_time = time.time()
|
||||
|
||||
processes = [multiprocessing.Process(target=run_sleep()) 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