gpt4 book ai didi

f# - 为什么这个计时功能总是测到0ms?

转载 作者:行者123 更新时间:2023-12-04 17:12:58 24 4
gpt4 key购买 nike

我正在为一些算法计时,并提出了下面的时间函数。但是,它始终返回 0 毫秒。

问题是为什么当它显然需要几秒钟时它总是 0ms。我是 F# 开发人员,所以我可能缺少一些概念。

请注意,问题不是关于更有效的斐波那契算法,我也知道该函数正在测量现实世界时间而不是 CPU 时间(可以通过 Sys.time() 获得)

let time f x =
let timer = new System.Diagnostics.Stopwatch()
timer. Start ( )
try f x finally
printf "Took %dms" timer.ElapsedMilliseconds;;

let rec fib x =
if x < 2 then 1
else fib(x-1) + fib(x-2)

time Array.iter (fun x -> ignore (fib x) ) [| 1 .. 40 |]

感谢您对 F# 初学者的任何帮助和指点

问候, 汤姆

最佳答案

问题是你的时间函数需要一个单参数函数,但你用一个双参数调用它:

time Array.iter (fun x -> ...) [|1..40|]
^- first arg ^- second arg

要获得您想要的结果,请使用括号
time (Array.iter (fun x -> ignore (fib x) )) [| 1 .. 40 |] 
^- a single partially curried function ^- a single argument

例如在 FSI 中:
> time ( Array.iter (fun x -> ignore (fib x) ) ) [| 1 .. 40 |];;
Took 6589msval it : unit = ()

更好的是,如果您在 F# 交互中进行测试,请使用 #time指令和 FSI 将为您安排时间。
例子:
> #time;;

--> Timing now on

> Array.iter (fun x -> ignore (fib x) ) [| 1 .. 40 |];;
Real: 00:00:06.816, CPU: 00:00:06.218, GC gen0: 0, gen1: 0, gen2: 0
val it : unit = ()

关于f# - 为什么这个计时功能总是测到0ms?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4828806/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com