Parallelism on single Core with .NET C# and SIMD / AVX. First Example.
Anonymous
7,785 views
Welcome!
This C# code will shows to us a simple basic examples of SIMD / AVX. We will compare the sum of two arrays of integers without SIMD and with it. The performance increasing is awesome!
The source code is on GitHub, please feel free to come up with proposals to improve it.
Hands-on Demo
Run this ready to use benchmark
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
// {
�using System;
using System.Diagnostics;
using System.Linq;
using System.Numerics;
namespace Answer
{
public class UniverseStub
{
static void allBench(int loop, int arraySize, int rerun)
{
Stopwatch sw = new Stopwatch();
Random random = new Random();
Func<int, int[]> genRandomIntArray = n => Enumerable.Repeat(0, n).Select(i => random.Next(2 * n)).ToArray();
Func<int, int[]> genRandomIntArray2 = n =>
{
int[] ar = new int[n];
for (int k = 0; k < n; ++k) ar[k] = random.Next(2 * n);
return ar;
};
Action<int, int> bench1 = (K, N) =>
{
sw.Restart();
int[] x = genRandomIntArray2(N);
int[] y = genRandomIntArray2(N);
int[] r = new int[N];
for (int k = 0; k < K; ++k)
{
for (int i = 0; i < N; ++i) r[i] = x[i] + y[i];
}
//Console.WriteLine(String.Join(" ", x.Take(10)));
//Console.WriteLine(String.Join(" ", y.Take(10)));
//Console.WriteLine(String.Join(" ", r.Take(10)));
Console.WriteLine($"Elapsed {sw.ElapsedMilliseconds,6} ms");
};
Action<int, int> bench2 = (K, N) =>
{
sw.Restart();
int[] x = genRandomIntArray2(N);
int[] y = genRandomIntArray2(N);
int[] r = new int[N];
Vector<int> v0 = Vector<int>.Zero;
for (int k = 0; k < K; ++k)
{
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Suggested playgrounds