Monday, August 6, 2012

F# Profiling: How to measure CPU time and absolute time?

Jon Harrop wrote a nice book, "F# for Scientists." In Chapter 8 of the book, he explained how to time the execution of a function in F#. Here I simply summarized what he said in the book and I revised his F# code examples to fit my needs.

Basically I'm interested in measuring the following two kinds of time:

  • Absolute time (or wall-clock time): the time elapsed in the real world.
  • CPU time: the amount of time that CPUs have spent running the function.
The .Net class System.Diagnostics.Stopwatch can be used to measure absolute time. And the TotalProcessorTime property of System.Diagnostics.Process returns a TimeSpan object, which indicates the amount of CPU time that the associated process has spent running the F# function.

///////////////////////////////////////////////////////////


open System.Diagnostics

let time f = 
    let proc = Process.GetCurrentProcess()
    let cpu_time_stamp = proc.TotalProcessorTime
    let timer = new Stopwatch()
    timer.Start()
    try
        f()
    finally
        let cpu_time = (proc.TotalProcessorTime-cpu_time_stamp).TotalMilliseconds
        printfn "CPU time = %dms" (int64 cpu_time)
        printfn "Absolute time = %dms" timer.ElapsedMilliseconds

let rec loop n f x =
    if n > 0 then
        f x |> ignore
        loop (n-1) f x

time (fun () -> loop 1000000 List.sum [1..100])

1 comment:

  1. It’s a very informative and helpful article, thank you for sharing!


    melbourne seo services

    ReplyDelete