From: William James Date: 2009-02-11T16:38:54+09:00 Subject: Re: Ruby vs Perl performance William James wrote: > Reid Thompson wrote: > > > Reid Thompson wrote: > > > > > > Ruby Elapsed 0.045477 > > > > > > > > #!/usr/local/bin/ruby > > > > require 'rubygems' > > require 'inline' > > > > BAILOUT = 16 > > MAX_ITERATIONS = 1000 > > > > class Mandelbrot > > > > def initialize > > puts "Rendering" > > for y in -39...39 do > > puts > > for x in -39...39 do > > i = iterate(x/40.0,y/40.0) > > if (i == 0) > > print "*" > > else > > print " " > > end > > end > > end > > end > > > > inline do |builder| > > builder.c " > > int iterate (double x, double y) > > { > > int BAILOUT = 16; > > int MAX_ITERATIONS = 1000; > > double cr = y-0.5; > > double ci = x; > > double zi = 0.0; > > double zr = 0.0; > > double zr2 = 0.0; > > double zi2 = 0.0; > > int i = 0; > > double temp = 0.0; > > > > while (1) > > { > > i += 1; > > temp = zr * zi; > > zr2 = zr * zr; > > zi2 = zi * zi; > > zr = zr2 - zi2 + cr; > > zi = temp + temp + ci; > > > > if ( zi2 + zr2 > BAILOUT) > > { > > return i; > > } > > if ( i > MAX_ITERATIONS) > > { > > return 0; > > } > > } > > }" > > end > > > > > end > > > > > > time = Time.now > > Mandelbrot.new > > puts > > puts "Ruby Elapsed %f" % (Time.now - time) > > > Using the functional language F#: > > 0.0400575999999999 on my laptop with 2GHz Pentium. > > let bailout = 16.0 > let max_iterations = 1000 > > > let iterate x y = > let cr = y - 0.5 and > ci = x and > zi = 0.0 and > zr = 0.0 in > let rec loop zi zr i = > if i > max_iterations then > 0 > else > let temp = zr * zi and > zr2 = zr * zr and > zi2 = zi * zi in > if zi2 + zr2 > bailout then > i > else > loop (temp + temp + ci) (zr2 - zi2 + cr) (i + 1) > in > loop zi zr 1 > > let mandelbrot () = > for y = -39 to 38 do > print_endline ""; > for x = -39 to 38 do > let i = iterate > (float x / 40.0) (float y / 40.0) in > System.Console.Write( ( if 0 = i then "*" else " " ) ) > done > done > > > let start_time = Sys.time () > let _ = mandelbrot (); > print_endline ""; > System.Console.Write (Sys.time () - start_time) Using the built-in type complex makes the program shorter but slower. open Math.Complex; let max_iterations = 1000 let iterate cmp = let rec loop z i = if i > max_iterations then 0 else if magnitude z >= 2.0 then i else loop (z * z + cmp) (i + 1) in loop zero 1 let mandelbrot () = for y = -39 to 38 do print_endline ""; for x = -39 to 38 do let i = iterate (complex ((float y / 40.0) - 0.5) (float x / 40.0)) in System.Console.Write( ( if 0 = i then "*" else " " ) ) done done let start_time = Sys.time () let _ = mandelbrot (); print_endline ""; System.Console.Write (Sys.time () - start_time)