2 people like it.

SIMD fold extension for Array

A SIMD enhanced fold function that adds on to the Array type

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
open System
open System.Numerics

type Array with    
    static member inline SIMDFold f h (start:'T) (values : 'T[]) =        
        let mutable i = 0;
        let mutable v = Vector<'T>(start)
        while i < values.Length - Vector<'T>.Count do            
            v <- f v (Vector<'T>(values,i))
            i <- i + Vector<'T>.Count
        i <- 0
        let mutable result = start        
        while i < Vector<'T>.Count do
            result <- h result v.[i]
            i <- i+1
        result

let example =
  let r = Random()
  Array.init 1000 (fun _ -> r.NextDouble())    
  |> Array.SIMDFold (fun a e -> a + e*e) (+) 0.0
namespace System
namespace System.Numerics
type Array =
  member Clone : unit -> obj
  member CopyTo : array:Array * index:int -> unit + 1 overload
  member GetEnumerator : unit -> IEnumerator
  member GetLength : dimension:int -> int
  member GetLongLength : dimension:int -> int64
  member GetLowerBound : dimension:int -> int
  member GetUpperBound : dimension:int -> int
  member GetValue : [<ParamArray>] indices:int[] -> obj + 7 overloads
  member Initialize : unit -> unit
  member IsFixedSize : bool
  ...

Full name: System.Array
static member Array.SIMDFold : f:('a -> 'b -> 'a) -> h:('T -> 'c -> 'T) -> start:'T -> values:'T [] -> 'T

Full name: Script.SIMDFold
val f : ('a -> 'b -> 'a)
val h : ('T -> 'c -> 'T)
val start : 'T
val values : 'T []
val mutable i : int
val mutable v : 'a
property Array.Length: int
val mutable result : 'T
val example : float

Full name: Script.example
val r : Random
Multiple items
type Random =
  new : unit -> Random + 1 overload
  member Next : unit -> int + 2 overloads
  member NextBytes : buffer:byte[] -> unit
  member NextDouble : unit -> float

Full name: System.Random

--------------------
Random() : unit
Random(Seed: int) : unit
val init : count:int -> initializer:(int -> 'T) -> 'T []

Full name: Microsoft.FSharp.Collections.Array.init
Random.NextDouble() : float
static member Array.SIMDFold : f:('a -> 'b -> 'a) -> h:('T -> 'c -> 'T) -> start:'T -> values:'T [] -> 'T
val a : int
val e : int
Raw view Test code New version

More information

Link:http://fssnip.net/7Qd
Posted:8 years ago
Author:Jack Mott
Tags: array , fold , simd