什么可能使未优化的 F# 代码比优化的代码更快?

问题描述 投票:0回答:1

因此,我决定尝试一下 F#,并将我用 C# 编写的算法移植到其中。在某一时刻,我注意到调试构建比发布构建运行得更快。然后我尝试了优化设置并得到了这些结果:

时间显示算法超过 100000 次运行的总执行时间。我使用的是 Visual Studio 2010 SP1 附带的 F# 编译器。目标平台是任何CPU。

Opt off, tail calls off: 5.81s
Opt off, tail calls on : 5.79s
Opt on , tail calls off: 6.48s
Opt on , tail calls on : 6.40s

我真的很困惑——为什么优化会让代码运行速度变慢?该算法的 C# 版本不会表现出这种行为(尽管它的实现方式略有不同)

这是 F# 代码的精简版本,它是一种查找分子模式的算法。这个 F# 程序依赖的所有代码都是用 F# 编写的。

namespace Motives
  module Internal = 
    type Motive = 
      { ResidueSet: Set<Residue>; AtomSet: Set<IAtom> }
      member this.Atoms : IAtom seq = 
        seq { 
          for r in this.ResidueSet do yield! r.Atoms
          yield! this.AtomSet
        }
      static member fromResidues (residues : Residue seq) = residues |> Seq.fold (fun (m: Set<Residue>) r -> m.Add(r)) Set.empty |> fun rs -> { ResidueSet = rs; AtomSet = Set.empty }
      static member fromAtoms (atoms : IAtom seq) = atoms |> Seq.fold (fun (m: Set<IAtom>) a -> m.Add(a)) Set.empty |>  fun atoms -> { ResidueSet = Set.empty; AtomSet = atoms }
      static member merge (m1: Motive) (m2: Motive) = { ResidueSet = Set.union m1.ResidueSet m2.ResidueSet; AtomSet = Set.union m1.AtomSet m2.AtomSet }
      static member distance (m1: Motive) (m2: Motive) = Seq.min (seq { for a in m1.Atoms do for b in m2.Atoms -> a.Position.DistanceTo(b.Position) })

    type Structure with 
      static member fromMotive (m: Motive) (parent: IStructure) (addBonds: bool) : IStructure = 
        let atoms = AtomCollection.FromUniqueAtoms(m.Atoms)
        let bonds = 
          match addBonds with 
          | true -> BondCollection.Create(atoms |> Seq.map (fun a -> parent.Bonds.[a]) |> Seq.concat)
          | _ -> BondCollection.Empty
        Structure.Create (parent.Id + "_" + atoms.[0].Id.ToString(), atoms, bonds)

    // KDTree used for range queries
    // AminoChains used for regex queries
    type StructureContext = 
      { Structure: IStructure; KDTree: Lazy<KDAtomTree>; AminoChains: Lazy<(Residue array * string) list> }
      static member create (structure: IStructure) =
        match structure.IsPdbStructure() with
        | false -> { Structure = structure; KDTree = Lazy.Create(fun () -> structure.Atoms.ToKDTree()); AminoChains = Lazy.CreateFromValue([]) }
        | true  -> 
          let aminoChains = new System.Func<(Residue array * string) list> (fun () ->
            let residues = structure.PdbResidues() |> Seq.filter (fun r -> r.IsAmino)
            residues
            |> Seq.groupBy (fun r -> r.ChainIdentifier)
            |> Seq.map (fun (k,rs) -> rs |> Array.ofSeq, String.concat "" (rs |> Seq.map (fun r -> r.ShortName)))
            |> List.ofSeq)
          { Structure = structure; KDTree = Lazy.Create(fun () -> structure.Atoms.ToKDTree()); AminoChains = Lazy.Create(aminoChains) }

    // Remember the named motives from named patterns
    type MatchContext = 
      { StructureContext: StructureContext; NamedMotives: Map<string, Motive> }
      static member merge (c1: MatchContext) (c2: MatchContext) = 
        { StructureContext = c1.StructureContext; NamedMotives = c2.NamedMotives |> Map.fold (fun m k v -> m.Add(k,v)) c1.NamedMotives }

    type MatchedMotive = Motive * MatchContext 

    type Pattern = 
      | EmptyPattern
      | GeneratingPattern of ( StructureContext -> MatchedMotive seq )
      | ConstraintPattern of ( MatchedMotive -> MatchedMotive option ) * Pattern
      static member matches (p: Pattern) (context: StructureContext) : MatchedMotive seq = 
        match p with  
        | GeneratingPattern generator -> generator context
        | ConstraintPattern (transform, pattern) ->
          Pattern.matches pattern context
          |> Seq.choose (fun m -> transform m)
        | _ -> Seq.empty

    let ringPattern (names: string list) =
      let fingerprint = 
        names 
        |> Seq.map (fun s -> ElementSymbol.Create(s).ToString()) 
        |> Seq.sort
        |> String.concat ""  
      let generator (context: StructureContext) =
        let rings = context.Structure.Rings().GetRingsByFingerprint(fingerprint)
        rings |> Seq.map (fun r -> Motive.fromAtoms r.Atoms, { StructureContext = context; NamedMotives = Map.empty })
      GeneratingPattern generator

  open Internal

  type MotiveFinder (pattern: string) =
    // I am using a hard coded pattern here for testing purposes
    let pattern = ringPattern ["C"; "C"; "C"; "C"; "C"; "O"]
    member this.Matches (structure: IStructure) =
      Pattern.matches pattern (StructureContext.create structure)
      |> Seq.map (fun (m, mc) -> Structure.fromMotive m mc.StructureContext.Structure false) 
      |> List.ofSeq 
      |> List.sortBy (fun s -> s.Atoms.[0].Id)

///////////////////////////////////////////////////////////////////
// performance test

let warmUp = (new MotiveFinder("")).Matches (StructureReader.ReadPdb(filename, computeBonds = true))
printfn "%i" (List.length warmUp)

let structure = StructureReader.ReadPdb(filename, computeBonds = true)
let stopWatch = System.Diagnostics.Stopwatch.StartNew()
let nruns = 100000
let result = 
  seq { 
    for i in 1 .. nruns do
      yield (new MotiveFinder("")).Matches structure 
  } |> Seq.nth (nruns-1)

stopWatch.Stop()
printfn "Time elapsed: %f seconds" stopWatch.Elapsed.TotalSeconds

编辑2:

我似乎已经将问题范围缩小到了 Set 类型的实现。

对于此代码:

let stopWatch = System.Diagnostics.Stopwatch.StartNew()
let runs = 1000000
let result = 
  seq {
    for i in 1 .. runs do
      let setA = [ 1 .. (i % 10) + 5 ] |> Set.ofList
      let setB = [ 1 .. (i % 10) + 5 ] |> Set.ofList
      yield Set.union setA setB
  } |> Seq.nth (runs - 1)

stopWatch.Stop()
printfn "Time elapsed: %f seconds" stopWatch.Elapsed.TotalSeconds
printfn "%A" result

优化关闭时我得到约 7.5 秒,优化开启时约 8.0 秒。仍然目标=任何CPU(我有i7-860处理器)。

编辑3: 在我发布之前的编辑后,我想我应该只在列表上尝试它。

所以对于

let stopWatch = System.Diagnostics.Stopwatch.StartNew()
let runs = 1000000
let result1 = 
  seq {
    for i in 1 .. runs do
      let list = [ 1 .. i % 100 + 5 ]
      yield list
  } |> Seq.nth (runs - 1)

stopWatch.Stop()
printfn "Time elapsed: %f seconds" stopWatch.Elapsed.TotalSeconds
printfn "%A" result1

我用 opt 得到了〜3秒。关闭,选择时约 3.5 秒。开。

编辑4:

如果我删除 seq 构建器并执行

let stopWatch = System.Diagnostics.Stopwatch.StartNew()
let runs = 1000000
let mutable ret : int list = []
for i in 1 .. runs do
  let list = [ 1 .. i % 100 + 5 ]
  ret <- list

stopWatch1.Stop()
printfn "Time elapsed: %f seconds" stopWatch.Elapsed.TotalSeconds
printfn "%A" ret

无论打开还是关闭优化,我都会得到大约 3 秒的时间。所以看来问题出在优化 seq 构建器代码的某个地方。

奇怪的是,我用 C# 编写了一个测试应用程序:

var watch = Stopwatch.StartNew();

int runs = 1000000;

var result = Enumerable.Range(1, runs)
  .Select(i => Microsoft.FSharp.Collections.ListModule.OfSeq(Enumerable.Range(1, i % 100 + 5)))
  .ElementAt(runs - 1);

watch.Stop();

Console.WriteLine(result);
Console.WriteLine("Time: {0}s", watch.Elapsed.TotalSeconds);

代码的运行速度几乎是 F# 解决方案的两倍,约为 1.7 秒。

编辑5:

根据与 Jon Harrop 的讨论,我发现了导致优化代码运行速度变慢的原因(我仍然不知道为什么)。

如果我将

Motive.Atoms
更改为

member this.Atoms : IAtom seq = 
  seq { 
    for r in this.ResidueSet do yield! r.Atoms
      yield! this.AtomSet
  }

member this.Atoms : IAtom seq = 
  Seq.append (this.ResidueSet |> Seq.collect (fun r -> r.Atoms)) this.AtomSet

然后程序在优化版本和非优化版本中运行约 7.1 秒。这比

seq
版本慢,但至少一致。

因此,F# 编译器似乎无法优化计算表达式,并且这样做实际上会使它们变慢。

optimization f#
1个回答
6
投票

我还可以观察到您的包装器代码和倒数第二个示例在启用优化的情况下运行速度稍慢,但差异小于 10%,尽管有些异常,但我对优化有时会略微降低性能并不感到惊讶。

我应该注意到,您的编码风格留下了很大的优化空间,但如果没有完整的源代码,我不可能帮助优化它。您的示例使用以下代码:

let result1 =
  seq {
    for i in 1 .. runs do
      let list = [ 1 .. i % 100 + 5 ]
      yield list
  } |> Seq.nth (runs - 1)

当它更短、更惯用并且速度更快时:

let result1 =
  Seq.init runs (fun i -> List.init ((i+1) % 100 + 5) ((+) 1))
  |> Seq.nth (runs - 1)

编辑

在下面的评论中,您说您想要执行函数参数,在这种情况下,我不会假设

Seq.nth
会为您执行此操作,因此我会使用
for
循环来代替:

let mutable list = []
for i=1 to runs do
  list <- List.init (i % 100 + 5) ((+) 1)
list

这仍然比原来快 9 倍。

© www.soinside.com 2019 - 2024. All rights reserved.