2012年9月16日日曜日

開発環境

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

その他参考書籍

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

起動引数(コマンドライン引数)でオンかオフの設定。

コード(TextWrangler)

sample.rb

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

def profile block_description, &block
  s = ARGV[0]
  if s == 'on'
    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 on
7526桁
25000回の倍化: 0.435621秒
百万までのカウント: 0.674239秒
$ ./sample.rb
7526桁
$

0 コメント:

コメントを投稿