#!/usr/bin/env perl
use strict;
use warnings;
use Time::HiRes qw(time);
use Devel::Size qw(size);
my $array_size = 5_000_000;
my @array0;
my @array1;
print "Testing preallocation.\n";
my $t0 = time();
$#array0 = $array_size-1;
for (my $i = 0; $i < $array_size; $i++) {
$array0[$i] = $i;
}
my $t0_delta = time() - $t0;
print scalar(@array0), " elements. Last element value is $array0[-1]\n";
printf "Array size is %-0.2f megabytes\n", size(\@array0)/1024/1024;
printf "With preallocation: %-0.4f seconds\n", $t0_delta;
print "\nTesting without preallocation.\n";
my $t1 = time();
for (my $j = 0; $j < $array_size; $j++) {
$array1[$j] = $j;
}
my $t1_delta = time() - $t1;
print scalar(@array1), " elements. Last element value is $array1[-1]\n";
printf "Array size is %-0.2f megabytes\n", size(\@array1)/1024/1024;
printf "Without preallocation: %-0.4f seconds\n", $t1_delta;
####
Testing preallocation.
5000000 elements. Last element value is 4999999
Array size is 38.15 megabytes
With preallocation: 0.3005 seconds
Testing without preallocation.
5000000 elements. Last element value is 4999999
Array size is 44.55 megabytes
Without preallocation: 0.2775 seconds
##
##
# spent 1.30s (1.30+49µs) within main::main which was called:
# once (1.30s+49µs) by main::RUNTIME at line 33
sub main {
8 1 600ns my $array_size = 5_000_000;
9
10 1 200ns my @array0;
11 my @array1;
12
13 1 12µs 1 6µs my $t0 = time();
# spent 6µs making 1 call to Time::HiRes::time
14 1 6.69ms $#array0 = $array_size-1;
15 1 601ms for (my $i = 0; $i < $array_size; $i++) {
16 $array0[$i] = $i;
17 }
18 1 21µs 1 5µs my $t0_delta = time() - $t0;
# spent 5µs making 1 call to Time::HiRes::time
19
20 1 2µs 1 300ns my $t1 = time();
# spent 300ns making 1 call to Time::HiRes::time
21 1 603ms for (my $j = 0; $j < $array_size; $j++) {
22 $array1[$j] = $j;
23 }
24
25 1 16µs 1 6µs my $t1_delta = time() - $t1;
# spent 6µs making 1 call to Time::HiRes::time
26
27 1 26µs 1 18µs print scalar(@array0), " elements. Last element value is $array0[-1]\n";
# spent 18µs making 1 call to main::CORE:print
28 1 12µs 1 9µs printf "With preallocation: %-0.4f seconds\n", $t0_delta;
# spent 9µs making 1 call to main::CORE:prtf
29 1 4µs 1 2µs print scalar(@array1), " elements. Last element value is $array1[-1]\n";
# spent 2µs making 1 call to main::CORE:print
30 1 89.3ms 1 3µs printf "Without preallocation: %-0.4f seconds\n", $t1_delta;
# spent 3µs making 1 call to main::CORE:prtf
31 }
32
33 1 7µs 1 1.30s main();
# spent 1.30s making 1 call to main::main