Reputation: 729
I have a laptop with a CPU Intel Core i3
and I want to create a simple program in Perl
to use 100% of CPU
capacity.
I have read about Threads
and search about running them parallel but I can't use 100% of the CPU
.
my code:
use strict;
use warnings;
use threads;
use threads::shared;
print "Starting main program\n";
my $t1 = threads->create(\&sub1, 1);
my $t2 = threads->create(\&sub1, 2);
my $t3 = threads->create(\&sub1, 3);
my $t4 = threads->create(\&sub1, 4);
$t1->join();
$t2->join();
$t3->join();
$t4->join();
print "End of main program\n";
sub sub1 {
my $num = 20;
print "started thread $num\n";
sleep $num;
print "done with thread $num\n";
return $num;
}
but after running CPU
usage is about 10%.
How do I use 100% of the CPU?
Upvotes: 3
Views: 331
Reputation: 1403
You're not using any CPU because the threads are sleeping - which tells the OS basically "I'm not doing anything, so use your resources elsewhere".
try some computation - like a nested loop with divisions and printing the result to /dev/null instead of sleeping.
Upvotes: 3
Reputation: 363807
You need to make the threads actually do something. E.g. make them count from 0 to a large number. Sleeping doesn't take CPU time.
Upvotes: 4