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

时间:2011-12-31 01:08:47

标签: optimization compiler-construction f#

所以我决定试试F#并将我用C#编写的算法移植到其中。有一次,我注意到调试版本的运行速度比版本1快。然后我玩了优化设置并得到了这些结果:

时间显示算法的总执行时间超过100000次运行。我正在使用Visual Studio 2010 SP1附带的F#编译器。目标平台是Any 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

EDIT2:

我似乎已经将问题缩小到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.5s的优化关闭和~8.0s的优化。仍然目标=任何CPU(我有i7-860处理器)。

EDIT3: 在我发布上一个编辑后,我想我应该只在列表上试一试。

所以

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

我选择了〜3s。选择关闭和~3.5秒。上。

EDIT4:

如果我删除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秒。

EDIT5:

根据与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.1s。哪个比seq版慢,但至少是一致的。

因此,似乎F#编译器无法优化计算表达式,并且实际上通过尝试使它们变慢。

1 个答案:

答案 0 :(得分: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倍。