開発環境
- OS X Lion - Apple(OS)
- BBEdit - Bare Bones Software, Inc.(Text Editor)
- プログラミング言語: Ruby
『初めてのプログラミング 第2版』(Chris Pine 著、長尾 高弘 訳、オライリー・ジャパン、2010年、ISBN978-4-87311-469-9)の 14章(ブロックとproc), 14.4(練習問題)よりよいプロファイリング を解いてみる。
その他参考書籍
- 『プログラミング言語 Ruby』David Flanagan, まつもと ゆきひろ 著 、卜部 昌平 監訳、長尾 高弘 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-394-4)
- Rubyクックブック ―エキスパートのための応用レシピ集
よりよいプロファイリング
コード(BBEdit)
sample.rb
#!/usr/bin/env ruby2.0
#-*- coding: utf-8 -*-
def profile block_description, &block
b = true # これで切り替え
if b
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.364203秒 百万までのカウント: 0.559518秒 $
プロファイリングをオフ(b = false)にした場合。
$ ./sample.rb 7526桁 $
ちなみにJavaScriptの場合。
コード(BBEdit)
$('#pre0').html("");
var n = parseInt($('#t0').val(), 10),
m = parseInt($('#t1').val(), 10),
profile = function( description, fn ) {
var $select = $('#on_off'),
b = $('option:selected', $select).val() === "on" ? true : false;
if ( b ) {
start = new Date().getTime();
fn();
duration = new Date().getTime() - start;
$('#pre0').append(description + ": " + duration / 1000 + "秒\n");
} else {
fn();
}
};
profile( n + "回の倍化", function ( ) {
var result = 1,
i;
for (i = 0 ; i < n; i += 1) {
result = result + result;
}
});
profile( m + "までのカウント", function ( ) {
var result = 0,
i;
for (i = 0; i < m; i += 1) {
result = result + 1;
}
});
pythonの場合。
sample.py
コード(BBEdit)
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
import time
def profile(description, fun):
b = True
if b:
start = time.time()
fun()
duration = time.time() - start
print("{0}: {1}秒".format(description, duration))
else:
fun()
def mul():
n = 1
for x in range(25000):
n = n + n
print("{0}桁".format(len(str(n))))
def count():
n = 0
for x in range(1000000):
n = n + 1
profile("25000の倍化", mul)
profile("百万までのカウント", count)
入出力結果(Terminal)
$ ./sample.py 7526桁 25000の倍化: 0.025408029556274414秒 百万までのカウント: 0.10909414291381836秒 $
0 コメント:
コメントを投稿