2012年10月23日火曜日

開発環境

『初めてのプログラミング 第2版』(Chris Pine 著、長尾 高弘 訳、オライリー・ジャパン、2010年、ISBN978-4-87311-469-9)の 13章(ブロックと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 '250,000回の倍化' do
  number = 1
  250_000.times do
    number = number + number
  end
  puts "#{number.to_s.length}桁"
end

profile '千万までのカウント' do
  number = 0
  10_000_000.times do
    number = number + 1
  end
end

入出力結果(Terminal)

$ ./sample.rb
75258桁
$

0 コメント:

コメントを投稿