簡體   English   中英

在 F# 中測量執行時間

[英]Measure time of execution in F#

請發布用於在 F# 中顯示時間的代碼。 我注意到您可以使用 #time 指令從 F# 交互中測量它,但我不知道如何從 FSI 執行程序

謝謝

我只會使用 .NET 秒表類。

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

來自 msdn:

#time本身切換是否顯示性能信息。 啟用后,F# Interactive 會測量被解釋和執行的每個代碼部分的實時時間、CPU 時間和垃圾回收信息。

因此,要測試您的函數,您必須打開 F# 交互式控制台並在其中執行您的函數(一種方法是選擇您的函數,右鍵單擊並選擇在交互式中執行)然后在交互式中調用您的函數,例如例子:

// 首先在交互式控制台或文檔中定義您的函數:

let square x = x * x

// in interactive
#time
square 10
#time

您將看到有多少實時時間和 CPU 時間用於計算以及來自垃圾收集器的一些信息

查看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    

雖然像這樣使用:

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

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

您還可以創建自定義計算表達式來隱藏實際的測量邏輯,例如:

timer {
   // your code goes here
}

在此處查看更多示例: https : //fsharpforfunandprofit.com/posts/computation-expressions-bind/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM