Yin Zhu
Yin Zhu

Reputation: 17119

a timeit function for F#

I am trying to write something like

let timeit (x:'a->'b) =
    let start = System.DateTime.Now
    x
    let duration = System.DateTime.Now - start
    printfn "time usage = %A" duration.Milliseconds 
    ()

it works for

let matrixtest() =
    let x = vector[1.;2.;4.]
    let y = matrix[[1.;2.;4.;];[3.;4.;9.;]]
    printfn "%A" (y * x)
    ()

but not for

let rec fib x = 
        match x with
        | 0 | 1 -> 1
        | n -> fib (n-1) + fib (n-2)

sa F# is static typed.

Any idea? Thanks.

Upvotes: 8

Views: 1201

Answers (4)

Dario
Dario

Reputation: 49218

Putting it together

let timeit f v = 
    let watch = new System.Diagnostics.Stopwatch()
    watch.Start()
    let res = f v 
    watch.Stop()
    printfn "Needed %f ms" (watch.Elapsed.TotalMilliseconds)
    res

Upvotes: 10

cfern
cfern

Reputation: 6006

When testing code in F# interactive, you can use the #time directive to time each piece of code you send to/enter in F# interactive. Example:

> #time;;

--> Timing now on

> let slowstring = List.fold (+) "" [for i in 1..10000 -> string i];;
Real: 00:00:00.544, CPU: 00:00:00.546, GC gen0: 464, gen1: 37, gen2: 0

val slowstring : string =
  "1234567891011121314151617181920212223242526272829303132333435"+[38833 chars]

> let quickstring = String.concat "" [for i in 1..10000 -> string i];;
Real: 00:00:00.008, CPU: 00:00:00.015, GC gen0: 0, gen1: 0, gen2: 0

val quickstring : string =
  "1234567891011121314151617181920212223242526272829303132333435"+[38833 chars]

> 

Upvotes: 8

kvb
kvb

Reputation: 55195

Even in the matrix case you need to apply the function to a value. Try this:

let timeit f v =
  let start = System.DateTime.Now
  let result = f v
  let duration = System.DateTime.Now - start
  printfn "time usage = %A" duration.Milliseconds 
  result

Aequitarum Custos is right about using the StopWatch class, though.

Upvotes: 4

Brett Allen
Brett Allen

Reputation: 5507

Use System.Diagnostics.Stopwatch

Much more accurate in timing.

This is assuming your getting a result of 0 seconds, which isn't DateTime.Now not working, it's just poor accuracy.

http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx

Upvotes: 7

Related Questions