-- Back to Index --
In this post I am doing IO bound
performance comparison.
First in Perl
:
#!/usr/bin/env perl
use v5.38;
use threads;
use LWP::Simple;
use Time::HiRes qw(time);
sub io_worker($id) {
my $url = "https://www.google.com";
my $content = get($url);
say "Thread $id finished.";
}
my $start_time = time();
my @threads = map { threads->create(\&io_worker, $_) } (1..9);
$_->join for @threads;
my $end_time = time();
printf("Total time taken: %.2f seconds\n", $end_time - $start_time);
Run the code now:
$ perl io-bound.pl
Thread 1 finished.
Thread 2 finished.
Thread 3 finished.
Thread 4 finished.
Thread 5 finished.
Thread 6 finished.
Thread 7 finished.
Thread 8 finished.
Thread 9 finished.
Total time taken: 0.34 seconds
$
Using HTTP::Tiny
as suggested by @leont
in the comments below:
#!/usr/bin/env perl
use v5.38;
use threads;
use HTTP::Tiny;
use Time::HiRes qw(time);
sub io_worker($id) {
my $url = "https://www.google.com";
my $content = HTTP::Tiny->new->get($url);
say "Thread $id finished.";
}
my $start_time = time();
my @threads = map { threads->create(\&io_worker, $_) } (1..9);
$_->join for @threads;
my $end_time = time();
printf("Total time taken: %.2f seconds\n", $end_time - $start_time);
Running the updated code now:
$ perl io-bound.pl
Thread 2 finished.
Thread 1 finished.
Thread 3 finished.
Thread 5 finished.
Thread 4 finished.
Thread 7 finished.
Thread 9 finished.
Thread 6 finished.
Thread 8 finished.
Total time taken: 0.30 seconds $
$
Let's do the same in Python
now:
#!/usr/bin/env python3
import time
import requests
import threading
def io_worker(id):
url = "https://www.google.com"
response = requests.get(url)
print(f"Thread {id} finished.")
start_time = time.time()
threads = []
for i in range(9):
thread = threading.Thread(target=io_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 io-bound.py
Thread 3 finished.
Thread 8 finished.
Thread 2 finished.
Thread 7 finished.
Thread 6 finished.
Thread 5 finished.
Thread 4 finished.
Thread 1 finished.
Thread 9 finished.
Total time taken: 0.24 seconds
$
CONCLUSION: With the result above, Python
with 0.24 seconds
is a clear winner against Perl
with 0.30 seconds
using HTTP::Tiny
and 0.34 seconds
using LWP::Simple
.
-- Back to Index --
Interestingly, if I run these with the
time
command, I get different results:So while the in-process timing seems to favour Python, the interpreter overhead (either in starting or exiting phase, or both), pulls them much closer together.