Diagonal scaling. Derived work from author: Neo Kim (@systemdesignone).

Code Snippet

simd.fsx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
#!/usr/bin/env -S dotnet fsi --langversion:8.0 --optimize --warnaserror+:25,26

#nowarn "60" 

(* Override implementations in augmentations are now deprecated. Override
   implementations should be given as part of the initial declaration of a type.
*)

#nowarn "9"

(* Uses of this construct may result in the generation of unverifiable .NET IL
   code.
*)

open System
open System.IO
open System.Numerics
open System.Runtime.Intrinsics
open System.Runtime.Intrinsics.X86 (* Avx2.IsSupported and Ssse3.IsSupported *)

open FSharp.NativeInterop

[<RequireQualifiedAccess>]
module Cache =
  
  (*

    # Cache-line size (64 bytes)

    ```sh
    cat /sys/devices/system/cpu/cpu0/cache/index0/coherency_line_size 
    64
    …
    cat /sys/devices/system/cpu/cpu0/cache/index3/coherency_line_size 
    64
    ```

    or

    ```sh
    getconf -a | grep CACHE
    LEVEL1_ICACHE_SIZE                 65536
    LEVEL1_ICACHE_ASSOC                
    LEVEL1_ICACHE_LINESIZE             64
    LEVEL1_DCACHE_SIZE                 32768
    LEVEL1_DCACHE_ASSOC                8
    LEVEL1_DCACHE_LINESIZE             64
    LEVEL2_CACHE_SIZE                  2097152
    LEVEL2_CACHE_ASSOC                 16
    LEVEL2_CACHE_LINESIZE              64
    LEVEL3_CACHE_SIZE                  25165824
    LEVEL3_CACHE_ASSOC                 12
    LEVEL3_CACHE_LINESIZE              64
    ```

    ## Remarks:

    * Size of L1 instruction cache (cache for storing the program) = 65536 bytes
      or 64 KB.

    * Size of L1 data cache (cache for storing the data) = 32768 bytes or 32 KB
      for each core.

    * L2 cache is present in each core of the CPU. Each core of CPU has 2 MB of
      cache.

    * But L3 cache is shared across all cores of the CPU. Total size of L3 cache
      is 24 MB.

  *)
  
  [<RequireQualifiedAccess>]
  module L1 =
    
    [<RequireQualifiedAccess>]
    module Data = 
  
      let size = 32_768
  
      [<RequireQualifiedAccess>]
      module Line =
    
        let size = 64
  
  [<RequireQualifiedAccess>]
  module L2 =
    
    let size = 2_097_152
    
    [<RequireQualifiedAccess>]
    module Line =
      
      let size = 64
  
  [<RequireQualifiedAccess>]
  module L3 =
    
    let size = 25_165_824
    
    [<RequireQualifiedAccess>]
    module Line =
      
      let size = 64

let inline roundPowTwo (i64:int64) =
  if 0L = i64 then
    0UL
  else
    let lzc = 63 - BitOperations .  LeadingZeroCount (value = uint64 i64)
    let tzc =      BitOperations . TrailingZeroCount (value = uint64 i64)
    if lzc = tzc then
      1UL <<< lzc
    else
      1UL <<< lzc + 1
  
let inline floorPowTwo (i64:int64) =
  if 0L = i64 then
    0UL
  else
    let lzc = 63 - BitOperations .  LeadingZeroCount (value = uint64 i64)
    let tzc =      BitOperations . TrailingZeroCount (value = uint64 i64)
    if lzc = tzc then
      roundPowTwo i64
    else
      roundPowTwo i64 >>> 1

(* Create binary files of size `n` filled with random bytes
let _ =

  let rand = new Random()
  let size = 32_768UL (* 32 KB *)
  //let size = 32_768UL * 1024UL (* 32 MB *)
  //let size = 32_768UL * 1024UL + 7UL * 1000UL * 1000UL (* 39 MB *)
  //let size = 4821UL * 1821UL * 1284UL + 774UL * 1872UL * 1383UL (* 13.27 GB *)
  // NOTE: The maximum index in any single dimension is 2,147,483,591
  //       (0x7FFFFFC7) for byte arrays and arrays of single-byte structures,
  //       and 2,146,435,071 (0X7FEFFFFF) for other types.
  let imax = 0x7FFFFFC7UL
  let carr =
    (* NOTE: Files greater than 2_147_483_591 bytes (2.14 GB) *)
    if imax < size then
      let len = int32 (size / imax)
      let arr =
        ( fun _ ->
          ( fun _ ->
              rand.Next(256)
              |> byte
          )
          |> Seq.init (int32 imax)
        )
        |> Seq.init len
      if size % imax = 0UL then
        arr
      else
        seq {
          arr
          ( fun _ ->
              rand.Next(256)
              |> byte
          )
          |> Seq.init (int32 (size % imax))
          |> Seq.singleton
        }
        |> Seq.concat
    (* NOTE: Files smaller or equal to 2_147_483_591 bytes (2.14 GB) *)
    else
      ( fun _ ->
          rand.Next(256)
          |> byte
      )
      |> Seq.init (int32 size)
      |> Seq.singleton
  
  let path =
    Path.Combine
      ( __SOURCE_DIRECTORY__
      , @"bin"
      , DateTimeOffset.UtcNow.ToUnixTimeSeconds()
        |> sprintf "%i.bin"
      )
  
  let _ =
    (* NOTE: `use` will call `IDispose` when leaving scope *)
    use file =
      File.Open
        ( path = path
        , mode = FileMode.OpenOrCreate
        , access = FileAccess.Write
        )
    carr
    |> Seq.iter (Seq.toArray >> file.Write >> file.Flush)

  00
*)

let path =
  (* 32 KB
  Path.Combine
    ( __SOURCE_DIRECTORY__
    , @"bin"
    , "1744965230.bin"
    )
  *)
  (* 32 MB
  Path.Combine
    ( __SOURCE_DIRECTORY__
    , @"bin"
    , "1744968938.bin"
    )
  *)
  (* 39 MB
  Path.Combine
    ( __SOURCE_DIRECTORY__
    , @"bin"
    , "1745027005.bin"
    )
  *)
  (* 13.27 GB
  *)
  Path.Combine
    ( __SOURCE_DIRECTORY__
    , @"bin"
    , "1745070391.bin"
    )
  
let size =
  if not (File.Exists path) then
    0L
  else
    FileInfo(fileName = path).Length

Avx2.IsSupported
|> printfn "* Avx2.IsSupported ............................................: %b"

Vector256.IsHardwareAccelerated
|> printfn "* Vector256.IsHardwareAccelerated .............................: %b"

printfn "* File: %s of size: %i bytes" path size

let look = 0x42uy
let hexa = look.ToString("X2") |> sprintf "0x%s"

#time "on"

(*
*)
let _ =

  let cache = Cache.L1.Data.size
  
  let _ =
    (* NOTE: `use` will call `IDispose` when leaving scope *)
    use file =
      File.Open
        ( path = path
        , mode = FileMode.Open
        , access = FileAccess.Read
        )
    let buff = Array.zeroCreate<byte> cache
    let rec loop acc =
      let road =
        file.Read
          ( buffer = buff
          , offset = 00  (* NOTE: We overwrite the buffer for each loop *)
          , count  = cache
          )
      if 0 < road then
        let len =
          Array.truncate road buff
          |> Array.map((=) look)
          |> Array.filter id
          |> Array.length
        loop (acc + len)
      else
        acc
    loop 0
    |> printfn "* Sequential.Core - the byte: %s appears: %i times" hexa

  00

#time "off"

#time "on"

(*
*)
let _ =

  let cache = Cache.L1.Data.size
  
  let _ =
    (* NOTE: `use` will call `IDispose` when leaving scope *)
    use file =
      File.Open
        ( path = path
        , mode = FileMode.Open
        , access = FileAccess.Read
        )
    let buff = Array.zeroCreate<byte> cache
    let vect = Vector256.Create<byte> (value = look)
    (* NOTE: Don't define pointers to the same data in the loop *)
    let addr0 = NativePtr.stackalloc<byte> Cache.L1.Data.Line.size
    let addr1 = NativePtr.add addr0 32
    let rec loop acc =
      let road =
        file.Read
          ( buffer = buff
          , offset = 00  (* NOTE: We overwrite the buffer for each loop *)
          , count  = cache
          )
      if 0 < road then
        let rec simd sum off =
          if off < road then
            let rec aux i =
              if Cache.L1.Data.Line.size > i then
                NativePtr.set addr0 i buff[i + off]
                aux (i + 1)
            aux 0
            (* NOTE: Load 32 bytes of the 64 Cache.L1.Data.Line.size into two
                     Vector256 each
            *)
            let v0 = Avx2.LoadVector256 (address = addr0)
            let v1 = Avx2.LoadVector256 (address = addr1)
            (* NOTE: Compare them to a Vector256 with all 32 bytes set to byte
                     we are looking for
            *)
            let c0 = Avx2.CompareEqual(left = vect, right = v0)
            let c1 = Avx2.CompareEqual(left = vect, right = v1)
            (* NOTE: If there was a match, the byte value in the new vectors
                     are set to 0xFFuy in c0 and c1. Convert those bytes to
                     a single bit in an int bitmask
            *)
            let m0 = Avx2.MoveMask(value = c0)
            let m1 = Avx2.MoveMask(value = c1)
            (* NOTE: Count the set bits in the bitmask as matches *)
            let b0 = BitOperations.PopCount(value = uint32 m0)
            let b1 = BitOperations.PopCount(value = uint32 m1)
            (* NOTE: And add each of them to accumulated sum *)
            Cache.L1.Data.Line.size + off
            |> simd (sum + b0 + b1)
          else
            sum
        let len =
          simd 0 0
        loop (acc + len)
      else
        acc
    loop 0
    |> printfn "* Sequential.SIMD - the byte: %s appears: %i times" hexa

  00

#time "off"

#time "on"

(*
*)
let _ =

  let cpus =
    int64 Environment.ProcessorCount (* CPU(s): 20 *)
    |> int32
  
  let size =
    if not (File.Exists path) then
      0L
    else
      FileInfo(fileName = path).Length
  
  let chunkPerCPU =
    size / int64 cpus
    |> roundPowTwo
    |> int64
  
  let cache =
    if Cache.L1.Data.size > int32 chunkPerCPU then
      int32 chunkPerCPU
    else
      Cache.L1.Data.size
  
  ( fun i ->
      let lower, upper =
        if size < chunkPerCPU * int64 i then
          Int64.MaxValue, Int64.MaxValue
        else
          let low = chunkPerCPU * int64 i
          let upp = chunkPerCPU + low
          low, upp
      if lower < size then
        (* NOTE: `use` will call `IDispose` when leaving scope *)
        use file =
          File.Open
            ( path   = path
            , mode   = FileMode.Open
            , access = FileAccess.Read
            , share  = FileShare.Read 
            )
        file.Position <- lower
        let buff = Array.zeroCreate<byte> cache
        let rec loop acc =
          if file.Position < upper then
            let road =
              file.Read
                ( buffer = buff
                , offset = 00  (* NOTE: We overwrite the buffer for each loop *)
                , count  = cache
                )
            let len =
              Array.truncate road buff
              |> Array.map((=) look)
              |> Array.filter id
              |> Array.length
            if 0 < len then
              loop (acc + len)
            else
              acc
          else
            acc
        loop 0
      else
        0
  )
  |> Array.Parallel.init cpus
  |> Array.sum
  |> printfn "* Concurrent.Core - the byte: %s appears: %i times" hexa

  00

#time "off"

#time "on"

(*
*)
let _ =

  let cpus =
    int64 Environment.ProcessorCount (* CPU(s): 20 *)
    |> int32
  
  let size =
    if not (File.Exists path) then
      0L
    else
      FileInfo(fileName = path).Length
  
  let chunkPerCPU =
    size / int64 cpus
    |> roundPowTwo
    |> int64
  
  let cache =
    if Cache.L1.Data.size > int32 chunkPerCPU then
      int32 chunkPerCPU
    else
      Cache.L1.Data.size
  
  ( fun i ->
      let lower, upper =
        if size < chunkPerCPU * int64 i then
          Int64.MaxValue, Int64.MaxValue
        else
          let low = chunkPerCPU * int64 i
          let upp = chunkPerCPU + low
          low, upp
      if lower < size then
        (* NOTE: `use` will call `IDispose` when leaving scope *)
        use file =
          File.Open
            ( path   = path
            , mode   = FileMode.Open
            , access = FileAccess.Read
            , share  = FileShare.Read 
            )
        file.Position <- lower
        let buff = Array.zeroCreate<byte> cache
        let vect = Vector256.Create<byte> (value = look)
        (* NOTE: Don't define pointers to the same data in the loop *)
        let addr0 = NativePtr.stackalloc<byte> Cache.L1.Data.Line.size
        let addr1 = NativePtr.add addr0 32
        let rec loop acc =
          if file.Position < upper then
            let road =
              file.Read
                ( buffer = buff
                , offset = 00 (* NOTE: We overwrite the buffer for each loop *)
                , count  = cache
                )
            if 0 < road then
              let rec simd sum off =
                if off < road then
                  let rec aux i =
                    if Cache.L1.Data.Line.size > i then
                      NativePtr.set addr0 i buff[i + off]
                      aux (i + 1)
                  aux 0
                  (* NOTE: Load 32 bytes of the 64 Cache.L1.Data.Line.size
                           into two Vector256 each
                  *)
                  let v0 = Avx2.LoadVector256 (address = addr0)
                  let v1 = Avx2.LoadVector256 (address = addr1)
                  (* NOTE: Compare them to a Vector256 with all 32 bytes set to
                           byte we are looking for
                  *)
                  let c0 = Avx2.CompareEqual(left = vect, right = v0)
                  let c1 = Avx2.CompareEqual(left = vect, right = v1)
                  (* NOTE: If there was a match, the byte value in the new
                           vectors are set to 0xFFuy in c0 and c1. Convert
                           those bytes to a single bit in an int bitmask
                  *)
                  let m0 = Avx2.MoveMask(value = c0)
                  let m1 = Avx2.MoveMask(value = c1)
                  (* NOTE: Count the set bits in the bitmask as matches *)
                  let b0 = BitOperations.PopCount(value = uint32 m0)
                  let b1 = BitOperations.PopCount(value = uint32 m1)
                  (* NOTE: And add each of them to accumulated sum *)
                  Cache.L1.Data.Line.size + off
                  |> simd (sum + b0 + b1)
                else
                  sum
              let len =
                simd 0 0
              if 0 < len then
                loop (acc + len)
              else
                acc
            else
              acc
          else
            acc
        loop 0
      else
        0
  )
  |> Array.Parallel.init cpus
  |> Array.sum
  |> printfn "* Concurrent.SIMD - the byte: %s appears: %i times" hexa

  00

#time "off"
One tool to rule them all. Derived work from author: Neo Kim (@systemdesignone).

Code Output:

[nix-shell:~/code/dotnet/src/simd]$ export DOTNET_gcServer=0x01
[nix-shell:~/code/dotnet/src/simd]$ export DOTNET_GCHeapCount=0x0C
[nix-shell:~/code/dotnet/src/simd]$ ./simd.fsx
* Avx2.IsSupported ............................................: true
* Vector256.IsHardwareAccelerated .............................: true
* File: ~/code/dotnet/src/simd/bin/1745070391.bin of size: 13276156068 bytes
* Sequential.Core - the byte: 0x42 appears: 51851759 times
Real: 00:00:13.954, CPU: 00:00:15.190, GC gen0: 83, gen1: 2, gen2: 1
* Sequential.SIMD - the byte: 0x42 appears: 51851759 times
Real: 00:00:10.558, CPU: 00:00:11.480, GC gen0: 50, gen1: 0, gen2: 0
* Concurrent.Core - the byte: 0x42 appears: 51851759 times
Real: 00:00:02.662, CPU: 00:00:30.930, GC gen0: 136, gen1: 1, gen2: 0
* Concurrent.SIMD - the byte: 0x42 appears: 51851759 times
Real: 00:00:01.572, CPU: 00:00:18.890, GC gen0: 83, gen1: 0, gen2: 0

[nix-shell:~/code/dotnet/src/simd]$ time(grep -oaP '\x42' ./bin/1745070391.bin | wc -l)
51851759

real    0m7.695s
user    0m6.742s
sys     0m1.106s

[nix-shell:~/code/dotnet/src/simd]$ ll bin/ 
total 13037408
-rw-r--r-- 1 johndoe users       32768 Apr 18 10:33 1744965230.bin
-rw-r--r-- 1 johndoe users    33554432 Apr 18 11:35 1744968938.bin
-rw-r--r-- 1 johndoe users    40554432 Apr 19 03:43 1745027005.bin
-rw-r--r-- 1 johndoe users 13276156068 Apr 19 15:46 1745070391.bin

[nix-shell:~/code/dotnet/src/simd]$
Superoptimization with concurrency/parallelism + SIMD

References: