Skip to content

Instantly share code, notes, and snippets.

@manwar
Last active March 1, 2025 17:17
CPU bound thread performance in Perl and Python.

-- Back to Index --


In this post, let's do the CPU bound thread performance in Perl and Python.

First in Perl as below:

[Source Code]

#!/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:

[Source Code]

#!/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 --


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment