我对 F# 很陌生。我试图了解如何在 F# 中获得快速代码。为此,我尝试编写两种方法 (IsPrime1
和IsPrime2
) 进行基准测试。我的代码是:
// Learn more about F# at http://fsharp.net
open System
open System.Diagnostics
#light
let isDivisible n d = n % d = 0
let IsPrime1 n =
Array.init (n-2) ((+) 2) |> Array.exists (isDivisible n) |> not
let rec hasDivisor n d =
match d with
| x when x < n -> (n % x = 0) || (hasDivisor n (d+1))
| _ -> false
let IsPrime2 n =
hasDivisor n 2 |> not
let SumOfPrimes max =
[|2..max|] |> Array.filter IsPrime1 |> Array.sum
let maxVal = 20000
let s = new Stopwatch()
s.Start()
let valOfSum = SumOfPrimes maxVal
s.Stop()
Console.WriteLine valOfSum
Console.WriteLine("IsPrime1: {0}", s.ElapsedMilliseconds)
//////////////////////////////////
s.Reset()
s.Start()
let SumOfPrimes2 max =
[|2..max|] |> Array.filter IsPrime2 |> Array.sum
let valOfSum2 = SumOfPrimes2 maxVal
s.Stop()
Console.WriteLine valOfSum2
Console.WriteLine("IsPrime2: {0}", s.ElapsedMilliseconds)
Console.ReadKey()
IsPrime1
需要 760 毫秒,而IsPrime2
相同的结果需要 260 毫秒。
这里发生了什么以及如何使我的代码更快?