src/Pure/General/timing.ML
changeset 42013 1694cc477045
parent 42012 2c3fe3cbebae
child 42042 264f8d0e899f
equal deleted inserted replaced
42012:2c3fe3cbebae 42013:1694cc477045
    17   include BASIC_TIMING
    17   include BASIC_TIMING
    18   type timing = {elapsed: Time.time, cpu: Time.time, gc: Time.time}
    18   type timing = {elapsed: Time.time, cpu: Time.time, gc: Time.time}
    19   type start
    19   type start
    20   val start: unit -> start
    20   val start: unit -> start
    21   val result: start -> timing
    21   val result: start -> timing
       
    22   val timing: ('a -> 'b) -> 'a -> timing * 'b
    22   val message: timing -> string
    23   val message: timing -> string
    23 end
    24 end
    24 
    25 
    25 structure Timing: TIMING =
    26 structure Timing: TIMING =
    26 struct
    27 struct
    55     val cpu = usr2 - usr + sys2 - sys + gc;
    56     val cpu = usr2 - usr + sys2 - sys + gc;
    56   in {elapsed = elapsed, cpu = cpu, gc = gc} end;
    57   in {elapsed = elapsed, cpu = cpu, gc = gc} end;
    57 
    58 
    58 end;
    59 end;
    59 
    60 
       
    61 fun timing f x =
       
    62   let
       
    63     val start = start ();
       
    64     val y = f x;
       
    65   in (result start, y) end;
       
    66 
    60 
    67 
    61 (* timing messages *)
    68 (* timing messages *)
    62 
    69 
    63 fun message {elapsed, cpu, gc} =
    70 fun message {elapsed, cpu, gc} =
    64   Time.toString elapsed ^ "s elapsed time, " ^
    71   Time.toString elapsed ^ "s elapsed time, " ^
    66   Time.toString gc ^ "s GC time" handle Time.Time => "";
    73   Time.toString gc ^ "s GC time" handle Time.Time => "";
    67 
    74 
    68 fun cond_timeit enabled msg e =
    75 fun cond_timeit enabled msg e =
    69   if enabled then
    76   if enabled then
    70     let
    77     let
    71       val timing_start = start ();
    78       val (timing, result) = timing (Exn.capture e) ();
    72       val res = Exn.capture e ();
    79       val end_msg = message timing;
    73       val end_msg = message (result timing_start);
    80       val _ =
    74       val _ = warning (if msg = "" then end_msg else msg ^ "\n" ^ end_msg);
    81         if Exn.is_interrupt_exn result then ()
    75     in Exn.release res end
    82         else warning (if msg = "" then end_msg else msg ^ "\n" ^ end_msg);
       
    83     in Exn.release result end
    76   else e ();
    84   else e ();
    77 
    85 
    78 fun timeit e = cond_timeit true "" e;
    86 fun timeit e = cond_timeit true "" e;
    79 fun timeap f x = timeit (fn () => f x);
    87 fun timeap f x = timeit (fn () => f x);
    80 fun timeap_msg msg f x = cond_timeit true msg (fn () => f x);
    88 fun timeap_msg msg f x = cond_timeit true msg (fn () => f x);