プログラミングGauche 17.5.3 メソッド適用のカスタマイズ 練習問題
2009年06月23日
<logger-generic>
をカスタマイズして、ログ出力の on/off を切り替える。
(use srfi-1) (use gauche.time) (define-class <logger-generic> (<generic>) ((printlog :init-value #f) ; スロットにログ出力フラグを追加 ())) (define-method apply-generic ((gf <logger-generic>) args) ; ログ出力制御 (if (ref gf 'printlog) (begin (format #t "args: ~s\n" args) (let ((return-value (next-method))) (format #t "result: ~s\n" return-value) return-value)) (next-method))) (define-class <profiler-generic> (<logger-generic>) ((counter :init-value 0) (time :init-form (make <real-time-counter>)))) (define-generic sub :class <profiler-generic>) (define-method apply-generic ((gf <profiler-generic>) args) (inc! (ref gf 'counter)) (with-time-counter (ref gf 'time) (next-method))) (define-method sub ((num1 <number>) (num2 <number>)) (- num1 num2)) (define-method get-profile ((gf <profiler-generic>)) (format #t "~s: ~d times called and spent time ~d\n" (ref gf 'name) (ref gf 'counter) (time-counter-value (ref gf 'time)))) (define-method init-profile ((gf <profiler-generic>)) (set! (ref gf 'counter) 0) (set! (ref gf 'time) (make <real-time-counter>)))
実行結果
ログ出力有りの場合
(set! (ref sub 'printlog) #t) (init-profile sub) (map sub (iota 10000 100 3) (iota 10000 300 5)) gosh> args: (100 300) result: -200 args: (103 305) result: -202 ... args: (30097 50295) result: -20198 (-200 -202 -204 -206 ... -20198) (get-profile sub) gosh> sub: 10000 times called and spent time 0.22919099999994788
ログ出力無しの場合
(set! (ref sub 'printlog) #f) (init-profile sub) (map sub (iota 10000 100 3) (iota 10000 300 5)) (get-profile sub) gosh> (-200 -202 -204 ... -20198) gosh> sub: 10000 times called and spent time 0.14352999999999677
プログラミングGauche
posted with amazlet at 08.11.14
Kahuaプロジェクト
オライリージャパン
売り上げランキング: 22775
オライリージャパン
売り上げランキング: 22775