简体   繁体   中英

let bindings and constructors in F#

I am defining a stopwatch in F#:

open System.Diagnostics

let UptimeStopwatch = Stopwatch.StartNew()

and I am printing every 3 seconds with

printfn "%A" UptimeStopwatch.Elapsed

and every time i'm getting "00:00:00.0003195" or something similarly small. Is F# calling the constructor every time I reference UptimeStopwatch? If so, how do I get around this ad achieve the desired result? This is a confusing intermingling of functional and imperative programming.

F# seems to interpret statements like

let MyFunction = DoSomething()

and

let MyFunction() = DoSomething()

differently. The first binds the return value of DoSomething() to the variable MyFunction , and the second binds the action DoSomething() to the function MyFunction() .

My usage of UptimeStopwatch was correct, and the error was elsewhere in my implementation.

I see you already found a problem elsewhere in your code, but the two lines in your question still take some time to run and, interestingly, you can make the overhead smaller.

When I run the two lines in your sample, it prints a value around 0.0002142. You can make that smaller by storing the elapsed time using let , because there is some overhead associated with constructing a representation of the printf format string (the first argument):

let UptimeStopwatch = Stopwatch.StartNew()
let elapsed = UptimeStopwatch.Elapsed
printfn "%A" elapsed

This prints on average a number around 0.0000878 (two times smaller). If you use Console , the result is similar (because the Elapsed property is obtained before Console is called and nothing else needs to be done in the meantime):

let UptimeStopwatch = Stopwatch.StartNew()
System.Console.WriteLine(UptimeStopwatch.Elapsed)

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