開発環境
- OS X Lion - Apple(OS)
- BBEdit - Bare Bones Software, Inc.(Text Editor)
- Script言語:Ruby
『初めてのプログラミング 第2版』(Chris Pine 著、長尾 高弘 訳、オライリー・ジャパン、2010年、ISBN978-4-87311-469-9)の 14章(block と proc), 14.4(練習問題)よりよいプロファイリング を解いてみる。
その他参考書籍
- 『プログラミング言語 Ruby』David Flanagan, まつもと ゆきひろ 著 、卜部 昌平 監訳、長尾 高弘 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-394-4)
- Rubyクックブック ―エキスパートのための応用レシピ集
よりよいプロファイリング
コード(BBEdit)
sample.rb
#!/usr/bin/env ruby1.9
#-*- coding: utf-8 -*-
def profile block_description, &block
bln = true
if bln
start_time = Time.new
block.call
duration = Time.new - start_time
puts "#{block_description}: #{duration}秒"
else
block.call
end
end
profile '25000回の倍化' do
number = 1
25000.times do
number = number + number
end
puts "#{number.to_s.length}桁"
end
profile '百万までのカウント' do
number = 0
1000000.times do
number = number + 1
end
end
入出力結果(Terminal)
$ ./sample.rb 7526桁 25000回の倍化: 0.062214秒 百万までのカウント: 0.136844秒 $
ちなみにJavaScriptの場合。
コード(BBEdit)
var profile = function (description, f) {
var bln = true,
start,
duration;
if (bln) {
start = new Date();
f();
duration = (new Date() - start) / 1000;
$('#pre0').append(description + ": " + duration + "秒\n");
} else {
f();
}
};
profile("100回の倍化", function (){
var number = 1,
i, max;
for (i = 0, max = 100; i < max; i += 1) {
number = number + number;
}
$('#pre0').append((number).toString().length + "桁\n");
});
profile("百までのカウント", function( ) {
var number = 0,
i, max;
for (i = 0, max = 100; i < max; i += 1) {
number = number + 1;
}
});
pythonの場合。
sample.py
コード(BBEdit)
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
def profile(description, f):
bln = True
if bln:
import time
start = time.time()
f()
duration = time.time() - start
print("{0}: {1}秒".format(description, duration))
else:
f()
def f():
number = 1
for x in range(25000):
number = number + number
print("{0}桁".format(len(str(number))))
def g():
number = 0
for x in range(1000000):
number = number + 1
profile("25000回の倍化", f)
profile("百万回の倍化", g)
入出力結果(Terminal)
$ ./sample.py 7526桁 25000回の倍化: 0.026067018508911133秒 百万回の倍化: 0.10782814025878906秒 $
perlの場合。
sample.pl
コード(BBEdit)
#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use 5.016;
binmode STDIN, ":utf8";
binmode STDOUT, ":utf8";
use Time::HiRes qw(gettimeofday);
use Math::BigInt;
sub profile {
my($description, $f) = @_;
my $bln = 1;
if ($bln) {
my $start = gettimeofday;
&$f;
my $duration = gettimeofday - $start;
print "$description: ${duration}秒\n";
} else {
&f();
}
}
profile("25000回の倍化", sub {
my $number = Math::BigInt->new(1);
for ((1..25000)) {
$number = $number + $number;
}
my $l = length ($number . "");
print $l . "桁\n";
});
profile("百万回までカウント", sub {
my $number = Math::BigInt->new();
for ((1..1000000)) {
$number = $number + 1;
}
});
入出力結果(Terminal)
$ ./sample.pl 7526桁 25000回の倍化: 5.46225810050964秒 百万回までカウント: 57.3425459861755秒 $
Math::BigIntモジュールが遅いからか、ruby, pythonと比べてperlが遅い。。(JavaScriptは25000回、百万回にしたらInfinityになっちゃうので100に制限。)
0 コメント:
コメントを投稿