fsprojects / FSharpPlus

Extensions for F#
https://fsprojects.github.io/FSharpPlus
Apache License 2.0
847 stars 94 forks source link

Stopwatch: measure function execution time #470

Open natalie-o-perret opened 2 years ago

natalie-o-perret commented 2 years ago

I discussed this idea with @gusty once on the fssf Slack, but just wanted to know if this could be relevant for the scope of FSharpPlus.

Lss,

[<RequireQualifiedAccess>]
module Stopwatch

open System.Diagnostics

let measure f =
    let stopwatch = Stopwatch.StartNew()
    let r = f()
    stopwatch.Stop()
    (r, stopwatch.Elapsed)

It's a simple helper, so not sure it is worthwhile to add it to the library

gusty commented 2 years ago

I am not sure, I have the feeling if there are other functions like this we can definitely add them. What do you think @wallymathieu @adz ?

adz commented 2 years ago

I was not aware of this class, but have made similar functions just using current time. I think it seems good.

The only other Stopwatch functionality amounts to being able to inspect seemingly constant IsHighResolution and Frequency (why are they instance fields then?) and to be able to continue timers.

I feel like these aren't generally useful, and the measurefunction is what you'd normally want.

gusty commented 2 years ago

Thanks, in terms of module and namespaces, what do you think it would be the best option for this and possible other related functions?

natalie-o-perret commented 2 years ago

The idea kinda stemmed from Matlab tic toc functions: https://www.mathworks.com/help/matlab/ref/tic.html

[<AbstractClass; Sealed>]
type private TicToc private () =

    static let Stopwatch = Stopwatch()

    static member Tic = Stopwatch.Restart
    static member Toc = Stopwatch.Elapsed

let tic = TicToc.Tic
let toc() = TicToc.Toc

This is a simplified version which doesn't support nested scope (unlike Matlab), an alternative impl. could be.

[<AbstractClass; Sealed>]
type private TicToc private () =

    static let Stopwatches = Queue<Stopwatch>()

    static member Tic = Stopwatch.StartNew >> Stopwatches.Value.Enqueue
    static member Toc = Stopwatches.Dequeue().Elapsed

let tic() = TicToc.Tic()
let toc() = TicToc.Toc
wallymathieu commented 2 years ago

Seems like a nice thing to have. I can see how this small utility method could fit in with scripting.

natalie-o-perret commented 2 years ago

Seems like a nice thing to have. I can see how this small utility method could fit in with scripting.

Agreed, in a scripting context, this can really come in handy to have shorthands like that.

Actually I'm wondering if there should be a scripting namespace 🤔

cannorin commented 2 years ago

something like FSharpPlus.Scripting sounds good?