[英]a timeit function for F#
我正在嘗試寫類似
let timeit (x:'a->'b) =
let start = System.DateTime.Now
x
let duration = System.DateTime.Now - start
printfn "time usage = %A" duration.Milliseconds
()
它適用於
let matrixtest() =
let x = vector[1.;2.;4.]
let y = matrix[[1.;2.;4.;];[3.;4.;9.;]]
printfn "%A" (y * x)
()
但不是
let rec fib x =
match x with
| 0 | 1 -> 1
| n -> fib (n-1) + fib (n-2)
F#是靜態類型的。
任何的想法? 謝謝。
把它放在一起
let timeit f v =
let watch = new System.Diagnostics.Stopwatch()
watch.Start()
let res = f v
watch.Stop()
printfn "Needed %f ms" (watch.Elapsed.TotalMilliseconds)
res
使用System.Diagnostics.Stopwatch
計時准確得多。
這是假設您得到0秒的結果,這不是DateTime.Now現在不起作用,它的准確性很差。
http://msdn.microsoft.com/zh-CN/library/system.diagnostics.stopwatch.aspx
在F#交互中測試代碼時,可以使用#time
指令來計時發送到/輸入在F#交互中的每段代碼的時間。 例:
> #time;;
--> Timing now on
> let slowstring = List.fold (+) "" [for i in 1..10000 -> string i];;
Real: 00:00:00.544, CPU: 00:00:00.546, GC gen0: 464, gen1: 37, gen2: 0
val slowstring : string =
"1234567891011121314151617181920212223242526272829303132333435"+[38833 chars]
> let quickstring = String.concat "" [for i in 1..10000 -> string i];;
Real: 00:00:00.008, CPU: 00:00:00.015, GC gen0: 0, gen1: 0, gen2: 0
val quickstring : string =
"1234567891011121314151617181920212223242526272829303132333435"+[38833 chars]
>
即使在矩陣情況下,您也需要將函數應用於值。 嘗試這個:
let timeit f v =
let start = System.DateTime.Now
let result = f v
let duration = System.DateTime.Now - start
printfn "time usage = %A" duration.Milliseconds
result
不過,Aequitarum Custos對於使用StopWatch
類是正確的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.