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.
You can use the magic command %%timeit to measure the execution time of the cell. As an example, try executing the same process using NumPy . As with %timeit , -n and -r are optional. Note that %%timeit measures the execution time of the entire cell, so the following example includes the time to import NumPy.
The “%timeit” is a line magic command in which the code consists of a single line or should be written in the same line for measuring the execution time. In the “%timeit” command, the particular code is specified after the “%timeit” is separated by a space.
timeit() runs the setup statement one time, then calls the main statement count times. It returns a single floating point value representing the cumulative amount of time spent running the main statement.
t = timeit( f ) measures the time (in seconds) required to run the function specified by the function handle f . In order to perform a robust measurement, timeit calls the specified function multiple times and returns the median of the measurements. If the function runs fast, timeit might call the function many times.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With