Created
August 25, 2020 15:59
-
-
Save badamczewski/22f046141bad49e7a16b8751ce97fabb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class BranchElimination | |
{ | |
int[] aTab; | |
int[] xTab; | |
int[] xInpTab; | |
[GlobalSetup] | |
public void Global() | |
{ | |
aTab = new int[5] { 10, 20, 30, 40, 50 }; | |
xTab = new int[4] { 100, 200, 300, 400 }; | |
int[] rndVals = new int[] { 50, 100, 150, 200, 250, 300, 350, 400, 450, 500 }; | |
Random rnd = new Random(); | |
xInpTab = new int[1024 * 4]; | |
for(int i = 0; i < 1024 * 4; i++) | |
{ | |
xInpTab[i] = rndVals[rnd.Next(0, 10)]; | |
} | |
} | |
[BenchmarkCategory("1"), Benchmark(Baseline = true)] | |
public int Branch() | |
{ | |
int cnt = 0; | |
for (int i = 0; i < xInpTab.Length; i++) | |
{ | |
var x = xInpTab[i]; | |
var a = 0; | |
if (x < xTab[2]) | |
{ | |
a = aTab[2]; | |
} | |
else if (x < xTab[3]) | |
{ | |
a = aTab[3]; | |
} | |
else | |
{ | |
a = aTab[4]; | |
} | |
cnt += a; | |
} | |
return cnt; | |
} | |
[BenchmarkCategory("1"), Benchmark] | |
public int Branchless() | |
{ | |
int cnt = 0; | |
for (int i = 0; i < xInpTab.Length; i++) | |
{ | |
var x = xInpTab[i]; | |
uint x_lt_x1 = (uint)((x - xTab[2]) >> 31); | |
uint x_lt_x2 = (uint)((x - xTab[3]) >> 31); | |
var result_0 = (int)((x_lt_x2 & aTab[3]) | (~x_lt_x2 & aTab[4])); | |
var result = (int)((x_lt_x1 & aTab[2]) | (~x_lt_x1 & result_0)); | |
cnt += result; | |
} | |
return cnt; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment