2013年1月3日木曜日

開発環境

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

その他参考書籍

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

コード(BBEdit)

sample.rb

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

def granfather_clock &block
  h = Time.new.hour
  h -= 12 if h > 13
  h.times do
    block.call
  end
end

puts "現在: #{Time.new}"
granfather_clock do
  puts "DOG!"
end

入出力結果(Terminal)

$ ./sample.rb
現在: 2013-01-03 18:07:49 +0900
DOG!
DOG!
DOG!
DOG!
DOG!
DOG!
$

ちなみにJavaScriptの場合。

コード(BBEdit)

function grandfather_clock(f){
  var td = new Date();
  var h = td.getHours();
  if(h > 12) h -= 12;
  for(var i = 0; i < h; i++){
    f();
  }
}
$('#d0').append("現在: " + new Date() + "\n");
grandfather_clock(function(){
  $('#pre0').append("DONG!\n");
});



pythonの場合。

sample.py

コード(BBEdit)

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

def grandfather_clock(f):
    import datetime
    h = datetime.datetime.now().hour
    if h > 12: h -= 12
    for x in range(h):
        f()

def f():
    print("DONG!")

grandfather_clock(f)

入出力結果(Terminal)

$ ./sample.py
DONG!
DONG!
DONG!
DONG!
DONG!
DONG!
$

perlの場合。

sample.pl

コード(BBEdit)

#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use 5.016;
binmode STDIN, ":utf8";
binmode STDOUT, ":utf8";

sub grandfather_clock{
  my $f = shift;
  my $h = (localtime)[2];
  $h -= 12 if $h > 12;
  for(1..$h){
    &$f;
  }
}

grandfather_clock(sub{
  print "DONG!\n";
});

入出力結果(Terminal)

$ ./sample.pl
DONG!
DONG!
DONG!
DONG!
DONG!
DONG!
$

0 コメント:

コメントを投稿