ck's archive: monty optimization

Monty Optimization (4 comments)

Seth looked through Python's random library, and found that one function, random.random(), is written in C. I thought it would only be fair to use it:

#!/usr/bin/python

import sys
import random

if len(sys.argv) == 2:
	rounds = int(sys.argv[1])
else:
	rounds = 1000

swap = 0
stay = 0

for i in range(rounds):
	if int(random.random()*3) == int(random.random()*3):
		stay += 1
	else:
		swap += 1

print "Stay:", stay
print "Swap:", swap

It also occurred to me that Perl is probably more efficient looping when it doesn't have to explicitly increment a variable on each pass, so I've change the Perl code's while loop to a foreach:

#!/usr/bin/perl

use strict;
use warnings;

my $rounds = shift || 1000;
my ($stay,$swap) = (0,0);

foreach ( 1..$rounds ) {
	(int(rand(3)) == int(rand(3))) ? $stay++ : $swap++;
};

print "Stay: $stay\nSwap: $swap\n";

But how much changed?

 % time ./monty.pl 1000000
Stay: 333343
Swap: 666657
./monty.pl 1000000  0.72s user 0.00s system 99% cpu 0.728 total
% time ./monty.py 1000000
Stay: 333168
Swap: 666832
./monty.py 1000000  2.85s user 0.02s system 99% cpu 2.894 total

Both programs sped up nicely, but Perl is still significantly faster than Python for this.

search the archives:

Main archive listing

Copyright © 2001-2012 Chris Kuehn