Subscribed unsubscribe Subscribe Subscribe

golang

流行り、だそうなのでハロワってみる

fib.c

#include <stdio.h>

int fib (int n)
{
    if ( n <= 2 ) {
        return 1;
    }
    return fib(n - 1) + fib(n - 2);
} 

int main(int argc, char *argv[])
{
    int n = atoi(argv[1]);
    printf("%d\n", fib(n));
    return 0;
}

fib.go

package main

import (
    "fmt"
    "os"
    "strconv"
)

func fib(n int) int {
    if n <= 2 {
        return 1
    }
    return fib(n - 2) + fib(n - 1)
}

func main() {
    n, _ := strconv.Atoi(os.Args[1])
    fmt.Printf("%d\n", fib(n))
}

コンパイル

$ gcc -o c.out fib.c
$ gccgo -o go.out fib.go

実行

$ time ./c.out 45
1134903170

real	0m5.939s
user	0m5.932s
sys	0m0.000s
$ time ./go.out 45
1134903170

real	0m10.412s
user	0m10.392s
sys	0m0.008s

へぇ

参考

$ time ./fib.pl 45
1134903170

real	12m33.123s
user	12m32.064s
sys	0m0.232s
$ perl --version

This is perl 5, version 14, subversion 2 (v5.14.2) built for x86_64-linux-gnu-thread-multi
(with 80 registered patches, see perl -V for more detail)

Copyright 1987-2011, Larry Wall

Perl may be copied only under the terms of either the Artistic License or the
GNU General Public License, which may be found in the Perl 5 source kit.

Complete documentation for Perl, including FAQ lists, should be found on
this system using "man perl" or "perldoc perl".  If you have access to the
Internet, point your browser at http://www.perl.org/, the Perl Home Page.