Measure time of execution in F#

守給你的承諾、 提交于 2019-12-03 19:44:36

问题


Please post code for displaying time in F#. I noticed that you can measure it from F# interactive with #time directive, but I don't know how to execute program from FSI

Thanks


回答1:


I would just use the .NET Stopwatch class.

let stopWatch = System.Diagnostics.Stopwatch.StartNew()
...
stopWatch.Stop()
printfn "%f" stopWatch.Elapsed.TotalMilliseconds



回答2:


From msdn:

By itself, #time toggles whether to display performance information. When it is enabled, F# Interactive measures real time, CPU time, and garbage collection information for each section of code that is interpreted and executed.

So to test you function you have to open F# interactive console and execute your function in it (one way to do it is to select your function, right click and chose Execute in Interactive) Then make a call to your function in Interactive like that for example:

// define your function first either in interactive console or in your document:

let square x = x * x

// in interactive
#time
square 10
#time

You will see how much of real time and CPU time were spent on computation and a bit of information from garbage collector




回答3:


Check out the timer function in the F Sharp Programming wikibook. It is defined like this:

let duration f = 
    let timer = new System.Diagnostics.Stopwatch()
    timer.Start()
    let returnValue = f()
    printfn "Elapsed Time: %i" timer.ElapsedMilliseconds
    returnValue    

Whilst being used like this:

let sample() = System.Threading.Thread.Sleep(2)

duration ( fun() -> sample() )
// or
duration sample


来源:https://stackoverflow.com/questions/4528355/measure-time-of-execution-in-f

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!