用F#测量执行时间

nan*_*nek 31 time f# measure

请在F#上发布用于显示时间的代码.我注意到你可以使用#time指令从F#interactive测量它,但我不知道如何从FSI执行程序

谢谢

Bro*_*ass 48

我只想使用.NET Stopwatch类.

let stopWatch = System.Diagnostics.Stopwatch.StartNew()
...
stopWatch.Stop()
printfn "%f" stopWatch.Elapsed.TotalMilliseconds
Run Code Online (Sandbox Code Playgroud)


Pom*_*utZ 28

来自msdn:

#time本身切换是否显示性能信息.启用后,F#Interactive会为解释和执行的每个代码段测量实时,CPU时间和垃圾回收信息.

因此,要测试您的功能,您必须打开F#交互式控制台并在其中执行您的功能(一种方法是选择您的功能,右键单击并选择交互式执行)然后在交互式中调用您的功能例:

//首先在交互式控制台或文档中定义您的函数:

let square x = x * x

// in interactive
#time
square 10
#time
Run Code Online (Sandbox Code Playgroud)

您将看到在计算上花费了多少实时和CPU时间以及垃圾收集器中的一些信息


Dav*_*ite 21

查看F Sharp Programming wikibook中的定时器功能.它的定义如下:

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

虽然像这样使用:

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

duration ( fun() -> sample() )
// or
duration sample
Run Code Online (Sandbox Code Playgroud)

  • 他们正在使用DateTime.Now来测量他们功能的时间,这几乎不能替代秒表计时器. (5认同)