简体   繁体   中英

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.

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

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

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]

> 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM