FSharpPlus icon indicating copy to clipboard operation
FSharpPlus copied to clipboard

Stopwatch: measure function execution time

Open natalie-o-perret opened this issue 4 years ago • 7 comments

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

natalie-o-perret avatar Oct 19 '21 11:10 natalie-o-perret

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 ?

gusty avatar Oct 19 '21 20:10 gusty

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.

adz avatar Oct 19 '21 21:10 adz

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

gusty avatar Oct 19 '21 22:10 gusty

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

natalie-o-perret avatar Oct 20 '21 03:10 natalie-o-perret

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

wallymathieu avatar Oct 20 '21 17:10 wallymathieu

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 🤔

natalie-o-perret avatar Oct 22 '21 14:10 natalie-o-perret

something like FSharpPlus.Scripting sounds good?

cannorin avatar Oct 23 '21 04:10 cannorin