2012年11月27日火曜日

開発環境

『初めてのプログラミング 第2版』(Chris Pine 著、長尾 高弘 訳、オライリー・ジャパン、2010年、ISBN978-4-87311-469-9)の 14章(ブロックとproc), 14.4(練習問題の続き)よりよいプロファイリング を解いてみる。

その他参考書籍

よりよいプロファイリング

コード(TextWrangler)

sample.rb

#!/usr/bin/env ruby1.9
# -*- coding: utf-8 -*-

def profile block_description, &block
  on_off = false #これで切り替え
  if on_off
    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.059489秒
百万までのカウント: 0.138475秒
$ ./sample.rb
7526桁
$

ちなみにJavaScriptの場合。

コード(TextWrangler)

// 第3引数の省略可能引数で切り替え
function profile(description, f, on_off){
  if(on_off){
    var start_time = new Date();
    f();
    var duration = (new Date() - start_time) / 1000;
    $('#pre0').append(description + ": "  + duration + "秒\n");
  } else {
    f();
  }
}

$('#pre0').append('オンで実行\n');
profile('25000回の倍化', function(){
  var n = 1;
  for(var i = 0; i < 25000; i++){
    n = n + n;
  }
  $('#pre0').append(n.toString().length + "桁\n");
}, true);
profile('百万までのカウント', function(){
  n = 0;
  for(var i = 0; i < 1000000; i++){
    n = n + 1;
  }
}, true);
$('#pre0').append('オフで実行\n');
profile('25000回の倍化', function(){
  var n = 1;
  for(var i = 0; i < 25000; i++){
    n = n + n;
  }
  $('#pre0').append(n.toString().length + "桁\n");
});
profile('百万までのカウント', function(){
  n = 0;
  for(var i = 0; i < 1000000; i++){
    n = n + 1;
  }
});



pythonの場合。

sample.py

コード(TextWrangler)

#!/usr/bin/env python3.3
# -*- coding: utf-8 -*-

def profile(description, f, on_off=False):
    if on_off:
        import time
        start_time = time.time()
        f()
        duration = time.time() - start_time
        print("{0}: {1}秒".format(description, duration))
    else:
        f()

def f():
    n = 1
    for x in range(25000):
        n = n + n
    print("{0}桁".format(len(str(n))))

def g():
    n = 0
    for x in range(1000000):
        n = n + 1

print("オンで実行")
profile('25000回の倍化', f, on_off=True)
profile('百万回のカウント', g, on_off=True)
print("オフで実行")
profile('25000回の倍化', f)
profile('百万回のカウント', g)

入出力結果(Terminal)

$ ./sample.py
オンで実行
7526桁
25000回の倍化: 0.026142120361328125秒
百万回のカウント: 0.11889410018920898秒
オフで実行
7526桁
$

0 コメント:

コメントを投稿