Search code examples
.netf#sleepstopwatch

Why doesn't Thread.Sleep register in Stopwatch?


I have the following program:

open System.Diagnostics
open System.Threading

[<EntryPoint>]
let main _ =
    let timer = Stopwatch ()
    printfn "begin"
    timer.Start ()
    Thread.Sleep 5000
    timer.Stop ()
    printfn "end"
    printfn "%i ms" timer.Elapsed.Milliseconds
    0

I was expecting it to print an elapsed time of 5000 ms or a bit more. It does pause for about 5 seconds between printing "begin" and "end". But it only prints "3 ms" or thereabouts. Why doesn't Stopwatch count the sleep time?


Solution

  • It's because the Elapsed property returns a TimeSpan, and the Milliseconds property of that TimeSpan is pretty small. If you use the ElapsedMilliseconds property, you should see a good value.

    [Edit] You can also use timer.Elapsed.TotalMilliseconds, (which is a float, not an int).