-- Back to Index --
In this post, let's do the CPU bound thread performance in Perl
and Python
.
First in Perl
as below:
#!/usr/bin/env perl
use v5.38;
use threads;
use Time::HiRes qw(time);
sub cpu_worker($id) {
my $result = 0;
for (my $i = 0; $i < 10_000_000; $i++) {
$result += sqrt($i);
}
say "Thread $id completed.";
}
my $start_time = time();
my @threads = map { threads->create(\&cpu_worker, $_) } (1..9);
$_->join for @threads;
my $end_time = time();
printf("Total time taken: %.2f seconds\n", $end_time - $start_time);
Time to run the code:
$ perl cpu-bound.pl
Thread 7 completed.
Thread 1 completed.
Thread 6 completed.
Thread 5 completed.
Thread 3 completed.
Thread 4 completed.
Thread 2 completed.
Thread 8 completed.
Thread 9 completed.
Total time taken: 0.36 seconds
$
Time to do in Python
now:
#!/usr/bin/env python3
import time
import math
import threading
def cpu_worker(id):
result = 0
for i in range(10_000_000):
result += math.sqrt(i)
print(f"Thread {id} completed.")
start_time = time.time()
threads = []
for i in range(9):
thread = threading.Thread(target=cpu_worker, args=(i + 1,))
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
end_time = time.time()
print(f"Total time taken: {end_time - start_time:.2f} seconds")
Run the code now:
$ py cpu-bound.py
Thread 3 completed.
Thread 1 completed.
Thread 4 completed.
Thread 2 completed.
Thread 7 completed.
Thread 9 completed.
Thread 5 completed.
Thread 6 completed.
Thread 8 completed.
Total time taken: 2.12 seconds
$
CONCLUSION: With the result above, Perl
with 0.36 seconds
is a clear winner against Python
with 2.12 seconds
.
-- Back to Index --