Skip to content

Instantly share code, notes, and snippets.

@funny-falcon
Created October 18, 2011 11:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save funny-falcon/1295228 to your computer and use it in GitHub Desktop.
Save funny-falcon/1295228 to your computer and use it in GitHub Desktop.
mandelbrot rubinius
# The Computer Language Benchmarks Game
# http://shootout.alioth.debian.org/
#
# contributed by Karl von Laudermann
# modified by Jeremy Echols
# modified by Detlef Reichl
# modified by Joseph LaFata
# modified by Peter Zotov
# modified by Brian Ford
# modified by Yura Sokolov
require 'benchmark'
size = ARGV.shift.to_i
unless String.respond_to?(:pattern)
class String
def self.pattern(n, c)
("" << c) * n
end
end
end
unless ''.respond_to?(:setbyte)
class String
def setbyte(i, b)
self[i] = b
end
end
end
class PointArith
def initialize
@ci = @cr = @zrzr = @zr = @zizi = @zi = 0.0
end
def init(ci, cr)
@ci, @cr = ci, cr
@zrzr = @zr = 0.0
@zizi = @zi = 0.0
end
def step
tr = @zrzr - @zizi + @cr
ti = 2.0*@zr*@zi + @ci
@zr, @zi = tr, ti
@zrzr = @zr*@zr
@zizi = @zi*@zi
@zrzr + @zizi > 4.0
end
end
def mandelbrot(size, io)
io.puts "P4\n#{size} #{size}"
byte_acc = 0
bit_num = 0
byte = 0
image_size = ((size + 7) / 8) * size
buf = String.pattern image_size, 0
pnt = PointArith.new
y = 0
while y < size
ci = (2.0*y/size)-1.0
x = 0
while x < size
cr = (2.0*x/size)-1.5
pnt.init(ci, cr)
escape = 1
i = 0
while i < 50
if pnt.step
escape = 0
i = 50
end
i += 1
end
byte_acc = (byte_acc << 1) | escape
bit_num += 1
# Code is very similar for these cases, but using separate blocks
# ensures we skip the shifting when it's unnecessary, which is most cases.
if (bit_num == 8)
buf.setbyte byte, byte_acc
byte_acc = 0
bit_num = 0
byte += 1
elsif (x == size - 1)
buf.setbyte byte, (byte_acc << (8 - bit_num))
byte_acc = 0
bit_num = 0
byte += 1
end
x += 1
end
y += 1
end
io.write(buf)
end
File.open('/dev/null', 'w') do |f|
200.times{ mandelbrot 24, f }
end
duration = Benchmark.measure do
mandelbrot size, STDOUT
end
STDERR.puts duration
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment