Eric Hodel (drbrain) wrote,
Eric Hodel
drbrain

I rock.

$ ./translate2.rb demo/factorial.rb > f.c
$ cc -dynamic -bundle -undefined suppress -flat_namespace  -g -O2 -pipe -fno-common -I /usr/local/lib/ruby/1.8/powerpc-darwin7.9.0 f.c -o F.bundle
$ ruby -I. -rF -e 'p F.new.factorial(5)'
120
$ time ruby -Idemo -rfactorial -e 'p F.new.factorial(9999)' > /dev/null

real    0m3.938s
user    0m3.360s
sys     0m0.080s
$ time ruby -I. -rF -e 'p F.new.factorial(9999)' > /dev/null

real    0m3.751s
user    0m3.340s
sys     0m0.060s

(but I don't expect a speed increase, the way it works)

$ cat f.c
// BEGIN METARUBY PREAMBLE
#include <ruby.h>
#define case_equal_long(x, y) (rb_funcall((x), rb_intern("==="), 1, (y)))
// END METARUBY PREAMBLE
// class F < Object

static VALUE
rrc_cF_factorial(VALUE __self, VALUE n) {
VALUE f;
VALUE x;
f = LONG2FIX(1);
x = n;
while (RTEST(rb_funcall(x, rb_intern(">="), 1, LONG2FIX(2)))) {
f = rb_funcall(f, rb_intern("*"), 1, x);
x = rb_funcall(x, rb_intern("-"), 1, LONG2FIX(1));
};
return f;
}

static VALUE
rrc_cF_main(VALUE __self) {
return rb_funcall(__self, rb_intern("factorial"), 1, LONG2FIX(5));
}

void
Init_F() {
VALUE rrc_cF = rb_define_class("F", rb_path2class("Object"));

rb_define_method(rrc_cF, "factorial", rrc_cF_factorial, 1);
rb_define_method(rrc_cF, "main", rrc_cF_main, 0);

}

Subscribe
  • Post a new comment

    Error

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.
  • 3 comments