Skip to content
Snippets Groups Projects
Commit bdffaca0 authored by Paul Chevalier's avatar Paul Chevalier
Browse files

jeje c

parent 89abcd85
No related branches found
No related tags found
No related merge requests found
{
"python.testing.pytestArgs": [
"."
],
"python.testing.unittestEnabled": false,
"python.testing.pytestEnabled": true
}
\ No newline at end of file
File added
File added
File added
File added
File added
import threading
import time
# Function to perform a computational task
def compute_task(start, end):
total = 0
for i in range(start, end):
total += i ** 2
return total
# Wrapper function for threading
def thread_wrapper(start, end, results, index):
results[index] = compute_task(start, end)
# Single-threaded execution
def single_threaded():
start_time = time.time()
compute_task(0, 10_000_000)
end_time = time.time()
return end_time - start_time
# Multi-threaded execution
def multi_threaded():
start_time = time.time()
num_threads = 4
step = 10_000_000 // num_threads
threads = []
results = [0] * num_threads
for i in range(num_threads):
t = threading.Thread(target=thread_wrapper, args=(i * step, (i + 1) * step, results, i))
threads.append(t)
t.start()
for t in threads:
t.join()
end_time = time.time()
return end_time - start_time
# Main function to compare performance
if __name__ == "__main__":
single_thread_time = single_threaded()
multi_thread_time = multi_threaded()
print(f"Single-threaded execution time: {single_thread_time:.4f} seconds")
print(f"Multi-threaded execution time: {multi_thread_time:.4f} seconds")
print("Multi-threading is faster!" if multi_thread_time < single_thread_time else "Single-threading is faster!")
\ No newline at end of file
File added
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment