int(rand() + 1), int(rand()) +1, and hashes

C. Abney cabney at
Sun Jul 16 01:05:58 CDT 2000

This is just plain wierd.  Why should adding an integer and a float be faster
than adding two integers? The only difference betweeen sub randint1 and
randint2 below is that int() is applied after 1 is added to the output of
rand() in randint1, but int is applied to rand() before the addition in
randint2.  This behavior is specific to hashes (not arrays) so I think there's
some heavy magic going on in the background.  Someone mentioned to me that
floats used as array indexes will be automagically truncated by Perl, and
it's possible this perk has masked a bug revealed in the hash example?

Anybody have any ideas (sorry about the labeling problem, below)?

[cabney at annelidia integer]$ ./
Benchmark: timing 500000 iterations of exclusive_a, exclusive_h, inclusive_a, inclusive_h...
exclusive_a:  4 wallclock secs ( 3.41 usr +  0.00 sys =  3.41 CPU)
exclusive_h: 14 wallclock secs (12.90 usr +  0.01 sys = 12.91 CPU)
inclusive_a:  2 wallclock secs ( 2.71 usr +  0.00 sys =  2.71 CPU)
inclusive_h:  4 wallclock secs ( 4.25 usr +  0.00 sys =  4.25 CPU)

=8<=========== ==============
#! /usr/bin/perl -w

use strict;
use Benchmark;

my ($r1, %h1, $r2, %h2 );
my ($r3, @a1, $r4, @a2 );

sub randint1 {
        $r1 = int( rand(4) + 1 );

sub randint2 {
        $r2 = int( rand(4) ) + 1;

sub randint3 {
        $r3 = int( rand(4) + 1 );

sub randint4 {
        $r4 = int( rand(4) ) + 1;

timethese (500000, {
        'inclusive_h' => \&randint1,
        'exclusive_h' => \&randint2,
        'inclusive_a' => \&randint3,
        'exclusive_a' => \&randint4,

#print "Using a hash:\n";
#print "int inclusive:\n";
#print "$_: $h1{$_}\n" for (keys %h1);
#print "\nint exclusive?:\n";
#print "$_: $h2{$_}\n" for (keys %h2);
#print "Using an array:\n";
#print "int inclusive:\n";
#print "$_: $a1[$_]\n" for (1..4);
#print "\nint exclusive?:\n";
#print "$_: $a2[$_]\n" for (1..4);
=8<=========== ==============

Any thoughts appreciated.

CA (thinking of typing 'which perlbug')
Mighty Mouse is a cartoon. Superman is a real guy. No way a cartoon could beat
up a real guy! -- Teddy                                               C. Abney


The posting address is: san-diego-pm-list at

List requests should be sent to: majordomo at

If you ever want to remove yourself from this mailing list,
you can send mail to <majordomo at> with the following
command in the body of your email message:

    unsubscribe san-diego-pm-list

If you ever need to get in contact with the owner of the list,
(if you have trouble unsubscribing, or have questions about the
list itself) send email to <owner-san-diego-pm-list at> .
This is the general rule for most mailing lists when you need
to contact a human.

More information about the San-Diego-pm mailing list