How to resolve the algorithm Time a function step by step in the Perl programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Time a function step by step in the Perl programming language
Table of Contents
Problem Statement
Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could include time used by other processes on the computer. This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Time a function step by step in the Perl programming language
Source code in the perl programming language
use Benchmark;
use Memoize;
sub fac1 {
my $n = shift;
return $n == 0 ? 1 : $n * fac1($n - 1);
}
sub fac2 {
my $n = shift;
return $n == 0 ? 1 : $n * fac2($n - 1);
}
memoize('fac2');
my $result = timethese(100000, {
'fac1' => sub { fac1(50) },
'fac2' => sub { fac2(50) },
});
Benchmark::cmpthese($result);
sub cpu_time {
my ($user,$system,$cuser,$csystem) = times;
$user + $system
}
sub time_it {
my $action = shift;
my $startTime = cpu_time();
$action->(@_);
my $finishTime = cpu_time();
$finishTime - $startTime
}
printf "Identity(4) takes %f seconds.\n", time_it(sub {@_}, 4);
# outputs "Identity(4) takes 0.000000 seconds."
sub sum {
my $x = shift;
foreach (0 .. 999999) {
$x += $_;
}
$x
}
printf "Sum(4) takes %f seconds.\n", time_it(\&sum, 4);
# outputs "Sum(4) takes 0.280000 seconds."
You may also check:How to resolve the algorithm Singly-linked list/Traversal step by step in the Erlang programming language
You may also check:How to resolve the algorithm Determinant and permanent step by step in the МК-61/52 programming language
You may also check:How to resolve the algorithm Reverse a string step by step in the M2000 Interpreter programming language
You may also check:How to resolve the algorithm Sorting algorithms/Selection sort step by step in the ActionScript programming language
You may also check:How to resolve the algorithm Mayan numerals step by step in the Python programming language