请发布在 F# 中显示时间的代码。我注意到您可以使用#time 指令从 F# 交互中测量它,但我不知道如何从 FSI 执行程序
谢谢
我只会使用 .NET Stopwatch 类。
let stopWatch = System.Diagnostics.Stopwatch.StartNew()
...
stopWatch.Stop()
printfn "%f" stopWatch.Elapsed.TotalMilliseconds
来自 msdn:
#time本身会切换是否显示性能信息。启用后,F# Interactive 会为解释和执行的每一段代码测量实时、CPU 时间和垃圾收集信息。
因此,要测试您的功能,您必须打开 F# 交互式控制台并在其中执行您的功能(一种方法是选择您的功能,右键单击并选择在 Interactive 中执行)然后像这样在 Interactive 中调用您的功能例子:
// 首先在交互式控制台或文档中定义您的函数:
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/