Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a timeit function for F#

Tags:

.net

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.

like image 495
Yin Zhu Avatar asked Dec 14 '09 18:12

Yin Zhu


People also ask

What does %% Timeit do in Python?

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.

How do you use %% Timeit in Jupyter?

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.

What value does Timeit return?

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.

What unit does Timeit use?

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.


1 Answers

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
like image 193
Dario Avatar answered Sep 24 '22 15:09

Dario