How to use Statement class of org.junit.runners.model package

Best junit code snippet using org.junit.runners.model.Statement

Run junit automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1package se.chalmers.ju2jmh.experiments.workloads;
2
3import org.junit.Rule;
4import org.junit.rules.TestRule;
5import org.junit.rules.Timeout;
6
7public class SqrtTimeoutRuleTest extends SqrtTest {
8
9    @Rule
10    public final TestRule emptyRuleField = Timeout.seconds(60);
11
12    @org.openjdk.jmh.annotations.State(org.openjdk.jmh.annotations.Scope.Thread)
13    public static class _Benchmark {
14
15        private _Payloads payloads;
16
17        private SqrtTimeoutRuleTest instance;
18
19        @org.openjdk.jmh.annotations.Benchmark
20        public void benchmark_testRunWorkloadOnce() throws java.lang.Throwable {
21            this.payloads.testRunWorkloadOnce.evaluate();
22        }
23
24        @org.openjdk.jmh.annotations.Benchmark
25        public void benchmark_testRunWorkloadTwice() throws java.lang.Throwable {
26            this.payloads.testRunWorkloadTwice.evaluate();
27        }
28
29        @org.openjdk.jmh.annotations.Benchmark
30        public void benchmark_testRunWorkloadThrice() throws java.lang.Throwable {
31            this.payloads.testRunWorkloadThrice.evaluate();
32        }
33
34        private static class _InstanceStatement extends org.junit.runners.model.Statement {
35
36            private final se.chalmers.ju2jmh.api.ThrowingConsumer<SqrtTimeoutRuleTest> payload;
37
38            private final _Benchmark benchmark;
39
40            public _InstanceStatement(se.chalmers.ju2jmh.api.ThrowingConsumer<SqrtTimeoutRuleTest> payload, _Benchmark benchmark) {
41                this.payload = payload;
42                this.benchmark = benchmark;
43            }
44
45            @java.lang.Override
46            public void evaluate() throws java.lang.Throwable {
47                this.payload.accept(this.benchmark.instance);
48            }
49        }
50
51        private static class _ClassStatement extends org.junit.runners.model.Statement {
52
53            private final se.chalmers.ju2jmh.api.ThrowingConsumer<SqrtTimeoutRuleTest> payload;
54
55            private final _Benchmark benchmark;
56
57            private final org.junit.runner.Description description;
58
59            private final org.junit.runners.model.FrameworkMethod frameworkMethod;
60
61            private _ClassStatement(se.chalmers.ju2jmh.api.ThrowingConsumer<SqrtTimeoutRuleTest> payload, _Benchmark benchmark, org.junit.runner.Description description, org.junit.runners.model.FrameworkMethod frameworkMethod) {
62                this.payload = payload;
63                this.benchmark = benchmark;
64                this.description = description;
65                this.frameworkMethod = frameworkMethod;
66            }
67
68            @java.lang.Override
69            public void evaluate() throws java.lang.Throwable {
70                this.benchmark.instance = new SqrtTimeoutRuleTest();
71                org.junit.runners.model.Statement statement = new _InstanceStatement(this.payload, this.benchmark);
72                statement = this.applyRule(this.benchmark.instance.emptyRuleField, statement);
73                statement.evaluate();
74            }
75
76            private org.junit.runners.model.Statement applyRule(org.junit.rules.TestRule rule, org.junit.runners.model.Statement statement) {
77                return se.chalmers.ju2jmh.api.Rules.apply(rule, statement, this.description);
78            }
79
80            private org.junit.runners.model.Statement applyRule(org.junit.rules.MethodRule rule, org.junit.runners.model.Statement statement) {
81                return se.chalmers.ju2jmh.api.Rules.apply(rule, statement, this.frameworkMethod, this.benchmark.instance);
82            }
83
84            public static org.junit.runners.model.Statement forPayload(se.chalmers.ju2jmh.api.ThrowingConsumer<SqrtTimeoutRuleTest> payload, String name, _Benchmark benchmark) {
85                org.junit.runner.Description description = se.chalmers.ju2jmh.api.Rules.description(SqrtTimeoutRuleTest.class, name);
86                org.junit.runners.model.FrameworkMethod frameworkMethod = se.chalmers.ju2jmh.api.Rules.frameworkMethod(SqrtTimeoutRuleTest.class, name);
87                org.junit.runners.model.Statement statement = new _ClassStatement(payload, benchmark, description, frameworkMethod);
88                return statement;
89            }
90        }
91
92        private static class _Payloads {
93
94            public org.junit.runners.model.Statement testRunWorkloadOnce;
95
96            public org.junit.runners.model.Statement testRunWorkloadTwice;
97
98            public org.junit.runners.model.Statement testRunWorkloadThrice;
99        }
100
101        @org.openjdk.jmh.annotations.Setup(org.openjdk.jmh.annotations.Level.Trial)
102        public void makePayloads() {
103            this.payloads = new _Payloads();
104            this.payloads.testRunWorkloadOnce = _ClassStatement.forPayload(SqrtTimeoutRuleTest::testRunWorkloadOnce, "testRunWorkloadOnce", this);
105            this.payloads.testRunWorkloadTwice = _ClassStatement.forPayload(SqrtTimeoutRuleTest::testRunWorkloadTwice, "testRunWorkloadTwice", this);
106            this.payloads.testRunWorkloadThrice = _ClassStatement.forPayload(SqrtTimeoutRuleTest::testRunWorkloadThrice, "testRunWorkloadThrice", this);
107        }
108    }
109}
110
Full Screen
copy
1package se.chalmers.ju2jmh.experiments.workloads;
2
3import org.junit.Rule;
4import org.junit.rules.TestRule;
5import org.junit.rules.Timeout;
6
7public class ToHexStringTimeoutRuleTest extends ToHexStringTest {
8
9    @Rule
10    public final TestRule emptyRuleField = Timeout.seconds(60);
11
12    @org.openjdk.jmh.annotations.State(org.openjdk.jmh.annotations.Scope.Thread)
13    public static class _Benchmark {
14
15        private _Payloads payloads;
16
17        private ToHexStringTimeoutRuleTest instance;
18
19        @org.openjdk.jmh.annotations.Benchmark
20        public void benchmark_testRunWorkloadOnce() throws java.lang.Throwable {
21            this.payloads.testRunWorkloadOnce.evaluate();
22        }
23
24        @org.openjdk.jmh.annotations.Benchmark
25        public void benchmark_testRunWorkloadTwice() throws java.lang.Throwable {
26            this.payloads.testRunWorkloadTwice.evaluate();
27        }
28
29        @org.openjdk.jmh.annotations.Benchmark
30        public void benchmark_testRunWorkloadThrice() throws java.lang.Throwable {
31            this.payloads.testRunWorkloadThrice.evaluate();
32        }
33
34        private static class _InstanceStatement extends org.junit.runners.model.Statement {
35
36            private final se.chalmers.ju2jmh.api.ThrowingConsumer<ToHexStringTimeoutRuleTest> payload;
37
38            private final _Benchmark benchmark;
39
40            public _InstanceStatement(se.chalmers.ju2jmh.api.ThrowingConsumer<ToHexStringTimeoutRuleTest> payload, _Benchmark benchmark) {
41                this.payload = payload;
42                this.benchmark = benchmark;
43            }
44
45            @java.lang.Override
46            public void evaluate() throws java.lang.Throwable {
47                this.payload.accept(this.benchmark.instance);
48            }
49        }
50
51        private static class _ClassStatement extends org.junit.runners.model.Statement {
52
53            private final se.chalmers.ju2jmh.api.ThrowingConsumer<ToHexStringTimeoutRuleTest> payload;
54
55            private final _Benchmark benchmark;
56
57            private final org.junit.runner.Description description;
58
59            private final org.junit.runners.model.FrameworkMethod frameworkMethod;
60
61            private _ClassStatement(se.chalmers.ju2jmh.api.ThrowingConsumer<ToHexStringTimeoutRuleTest> payload, _Benchmark benchmark, org.junit.runner.Description description, org.junit.runners.model.FrameworkMethod frameworkMethod) {
62                this.payload = payload;
63                this.benchmark = benchmark;
64                this.description = description;
65                this.frameworkMethod = frameworkMethod;
66            }
67
68            @java.lang.Override
69            public void evaluate() throws java.lang.Throwable {
70                this.benchmark.instance = new ToHexStringTimeoutRuleTest();
71                org.junit.runners.model.Statement statement = new _InstanceStatement(this.payload, this.benchmark);
72                statement = this.applyRule(this.benchmark.instance.emptyRuleField, statement);
73                statement.evaluate();
74            }
75
76            private org.junit.runners.model.Statement applyRule(org.junit.rules.TestRule rule, org.junit.runners.model.Statement statement) {
77                return se.chalmers.ju2jmh.api.Rules.apply(rule, statement, this.description);
78            }
79
80            private org.junit.runners.model.Statement applyRule(org.junit.rules.MethodRule rule, org.junit.runners.model.Statement statement) {
81                return se.chalmers.ju2jmh.api.Rules.apply(rule, statement, this.frameworkMethod, this.benchmark.instance);
82            }
83
84            public static org.junit.runners.model.Statement forPayload(se.chalmers.ju2jmh.api.ThrowingConsumer<ToHexStringTimeoutRuleTest> payload, String name, _Benchmark benchmark) {
85                org.junit.runner.Description description = se.chalmers.ju2jmh.api.Rules.description(ToHexStringTimeoutRuleTest.class, name);
86                org.junit.runners.model.FrameworkMethod frameworkMethod = se.chalmers.ju2jmh.api.Rules.frameworkMethod(ToHexStringTimeoutRuleTest.class, name);
87                org.junit.runners.model.Statement statement = new _ClassStatement(payload, benchmark, description, frameworkMethod);
88                return statement;
89            }
90        }
91
92        private static class _Payloads {
93
94            public org.junit.runners.model.Statement testRunWorkloadOnce;
95
96            public org.junit.runners.model.Statement testRunWorkloadTwice;
97
98            public org.junit.runners.model.Statement testRunWorkloadThrice;
99        }
100
101        @org.openjdk.jmh.annotations.Setup(org.openjdk.jmh.annotations.Level.Trial)
102        public void makePayloads() {
103            this.payloads = new _Payloads();
104            this.payloads.testRunWorkloadOnce = _ClassStatement.forPayload(ToHexStringTimeoutRuleTest::testRunWorkloadOnce, "testRunWorkloadOnce", this);
105            this.payloads.testRunWorkloadTwice = _ClassStatement.forPayload(ToHexStringTimeoutRuleTest::testRunWorkloadTwice, "testRunWorkloadTwice", this);
106            this.payloads.testRunWorkloadThrice = _ClassStatement.forPayload(ToHexStringTimeoutRuleTest::testRunWorkloadThrice, "testRunWorkloadThrice", this);
107        }
108    }
109}
110
Full Screen
copy
1package se.chalmers.ju2jmh.experiments.workloads;
2
3import org.junit.Rule;
4import org.junit.rules.TestRule;
5import org.junit.rules.Timeout;
6
7public class ParseJavaSourceTimeoutRuleTest extends ParseJavaSourceTest {
8
9    @Rule
10    public final TestRule emptyRuleField = Timeout.seconds(60);
11
12    @org.openjdk.jmh.annotations.State(org.openjdk.jmh.annotations.Scope.Thread)
13    public static class _Benchmark {
14
15        private _Payloads payloads;
16
17        private ParseJavaSourceTimeoutRuleTest instance;
18
19        @org.openjdk.jmh.annotations.Benchmark
20        public void benchmark_testRunWorkloadOnce() throws java.lang.Throwable {
21            this.payloads.testRunWorkloadOnce.evaluate();
22        }
23
24        @org.openjdk.jmh.annotations.Benchmark
25        public void benchmark_testRunWorkloadTwice() throws java.lang.Throwable {
26            this.payloads.testRunWorkloadTwice.evaluate();
27        }
28
29        @org.openjdk.jmh.annotations.Benchmark
30        public void benchmark_testRunWorkloadThrice() throws java.lang.Throwable {
31            this.payloads.testRunWorkloadThrice.evaluate();
32        }
33
34        private static class _InstanceStatement extends org.junit.runners.model.Statement {
35
36            private final se.chalmers.ju2jmh.api.ThrowingConsumer<ParseJavaSourceTimeoutRuleTest> payload;
37
38            private final _Benchmark benchmark;
39
40            public _InstanceStatement(se.chalmers.ju2jmh.api.ThrowingConsumer<ParseJavaSourceTimeoutRuleTest> payload, _Benchmark benchmark) {
41                this.payload = payload;
42                this.benchmark = benchmark;
43            }
44
45            @java.lang.Override
46            public void evaluate() throws java.lang.Throwable {
47                this.payload.accept(this.benchmark.instance);
48            }
49        }
50
51        private static class _ClassStatement extends org.junit.runners.model.Statement {
52
53            private final se.chalmers.ju2jmh.api.ThrowingConsumer<ParseJavaSourceTimeoutRuleTest> payload;
54
55            private final _Benchmark benchmark;
56
57            private final org.junit.runner.Description description;
58
59            private final org.junit.runners.model.FrameworkMethod frameworkMethod;
60
61            private _ClassStatement(se.chalmers.ju2jmh.api.ThrowingConsumer<ParseJavaSourceTimeoutRuleTest> payload, _Benchmark benchmark, org.junit.runner.Description description, org.junit.runners.model.FrameworkMethod frameworkMethod) {
62                this.payload = payload;
63                this.benchmark = benchmark;
64                this.description = description;
65                this.frameworkMethod = frameworkMethod;
66            }
67
68            @java.lang.Override
69            public void evaluate() throws java.lang.Throwable {
70                this.benchmark.instance = new ParseJavaSourceTimeoutRuleTest();
71                org.junit.runners.model.Statement statement = new _InstanceStatement(this.payload, this.benchmark);
72                statement = this.applyRule(this.benchmark.instance.emptyRuleField, statement);
73                statement.evaluate();
74            }
75
76            private org.junit.runners.model.Statement applyRule(org.junit.rules.TestRule rule, org.junit.runners.model.Statement statement) {
77                return se.chalmers.ju2jmh.api.Rules.apply(rule, statement, this.description);
78            }
79
80            private org.junit.runners.model.Statement applyRule(org.junit.rules.MethodRule rule, org.junit.runners.model.Statement statement) {
81                return se.chalmers.ju2jmh.api.Rules.apply(rule, statement, this.frameworkMethod, this.benchmark.instance);
82            }
83
84            public static org.junit.runners.model.Statement forPayload(se.chalmers.ju2jmh.api.ThrowingConsumer<ParseJavaSourceTimeoutRuleTest> payload, String name, _Benchmark benchmark) {
85                org.junit.runner.Description description = se.chalmers.ju2jmh.api.Rules.description(ParseJavaSourceTimeoutRuleTest.class, name);
86                org.junit.runners.model.FrameworkMethod frameworkMethod = se.chalmers.ju2jmh.api.Rules.frameworkMethod(ParseJavaSourceTimeoutRuleTest.class, name);
87                org.junit.runners.model.Statement statement = new _ClassStatement(payload, benchmark, description, frameworkMethod);
88                return statement;
89            }
90        }
91
92        private static class _Payloads {
93
94            public org.junit.runners.model.Statement testRunWorkloadOnce;
95
96            public org.junit.runners.model.Statement testRunWorkloadTwice;
97
98            public org.junit.runners.model.Statement testRunWorkloadThrice;
99        }
100
101        @org.openjdk.jmh.annotations.Setup(org.openjdk.jmh.annotations.Level.Trial)
102        public void makePayloads() {
103            this.payloads = new _Payloads();
104            this.payloads.testRunWorkloadOnce = _ClassStatement.forPayload(ParseJavaSourceTimeoutRuleTest::testRunWorkloadOnce, "testRunWorkloadOnce", this);
105            this.payloads.testRunWorkloadTwice = _ClassStatement.forPayload(ParseJavaSourceTimeoutRuleTest::testRunWorkloadTwice, "testRunWorkloadTwice", this);
106            this.payloads.testRunWorkloadThrice = _ClassStatement.forPayload(ParseJavaSourceTimeoutRuleTest::testRunWorkloadThrice, "testRunWorkloadThrice", this);
107        }
108    }
109}
110
Full Screen
copy
1// CPP program to demonstrate processing
2// time of sorted and unsorted array
3#include <iostream>
4#include <algorithm>
5#include <ctime>
6using namespace std;
7
8const int N = 100001;
9
10int main()
11{
12    int arr[N];
13
14    // Assign random values to array
15    for (int i=0; i<N; i++)
16        arr[i] = rand()%N;
17
18    // for loop for unsorted array
19    int count = 0;
20    double start = clock();
21    for (int i=0; i<N; i++)
22        if (arr[i] < N/2)
23            count++;
24
25    double end = clock();
26    cout << "Time for unsorted array :: "
27        << ((end - start)/CLOCKS_PER_SEC)
28        << endl;
29    sort(arr, arr+N);
30
31    // for loop for sorted array
32    count = 0;
33    start = clock();
34
35    for (int i=0; i<N; i++)
36        if (arr[i] < N/2)
37            count++;
38
39    end = clock();
40    cout << "Time for sorted array :: "
41        << ((end - start)/CLOCKS_PER_SEC)
42        << endl;
43
44    return 0;
45}
46
Full Screen
copy
1Already sorted    32995 milliseconds
2Shuffled          125944 milliseconds
3
4Already sorted    18610 milliseconds
5Shuffled          133304 milliseconds
6
7Already sorted    17942 milliseconds
8Shuffled          107858 milliseconds
9
Full Screen
copy
1void run(vector<int>& v, const string& label)
2{
3    auto t0 = system_clock::now();
4    sort(v.begin(), v.end());
5    auto t1 = system_clock::now();
6    cout << label
7         << duration_cast<microseconds>(t1 — t0).count()
8         << " milliseconds\n";
9}
10
11void tst()
12{
13    vector<int> v(1'000'000);
14    iota(v.begin(), v.end(), 0);
15    run(v, "already sorted ");
16    std::shuffle(v.begin(), v.end(), std::mt19937{ std::random_device{}() });
17    run(v, "shuffled    ");
18}
19
Full Screen
copy
1#include <algorithm>
2#include <ctime>
3#include <iostream>
4
5int main() {
6    int data[32768]; const int l = sizeof data / sizeof data[0];
7
8    for (unsigned c = 0; c < l; ++c)
9        data[c] = std::rand() % 256;
10
11    // sort 200-element segments, not the whole array
12    for (unsigned c = 0; c + 200 <= l; c += 200)
13        std::sort(&data[c], &data[c + 200]);
14
15    clock_t start = clock();
16    long long sum = 0;
17
18    for (unsigned i = 0; i < 100000; ++i) {
19        for (unsigned c = 0; c < sizeof data / sizeof(int); ++c) {
20            if (data[c] >= 128)
21                sum += data[c];
22        }
23    }
24
25    std::cout << static_cast<double>(clock() - start) / CLOCKS_PER_SEC << std::endl;
26    std::cout << "sum = " << sum << std::endl;
27}
28
Full Screen
copy
1% Processing time with Sorted data vs unsorted data
2%==========================================================================
3% Generate data
4arraySize = 32768
5sum = 0;
6% Generate random integer data from range 0 to 255
7data = randi(256, arraySize, 1);
8
9
10%Sort the data
11data1= sort(data); % data1= data  when no sorting done
12
13
14%Start a stopwatch timer to measure the execution time
15tic;
16
17for i=1:100000
18
19    for j=1:arraySize
20
21        if data1(j)>=128
22            sum=sum + data1(j);
23        end
24    end
25end
26
27toc;
28
29ExeTimeWithSorting = toc - tic;
30
Full Screen
copy
1  a: Elapsed time (without sorting) = 3479.880861 seconds.
2  b: Elapsed time (with sorting ) = 2377.873098 seconds.
3
Full Screen
copy
1  a: Elapsed time (without sorting) = 19.8761 sec.
2  b: Elapsed time (with sorting ) = 7.37778 sec.
3
Full Screen
copy
1____________________________________________________________________________________
2- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT
4
Full Screen
copy
1___________________________________________ Straight road
2 |_________________________________________|Longer road
3
Full Screen
copy
1 // sort backwards (higher values first), may be in some other part of the code
2 std::sort(data, data + arraySize, std::greater<int>());
3
4 for (unsigned c = 0; c < arraySize; ++c) {
5       if (data[c] < 128) {
6              break;
7       }
8       sum += data[c];               
9 }
10
Full Screen
copy
1MOV R0, #0   // R0 = sum = 0
2MOV R1, #0   // R1 = c = 0
3ADR R2, data // R2 = addr of data array (put this instruction outside outer loop)
4.inner_loop  // Inner loop branch label
5    LDRB R3, [R2, R1]   // R3 = data[c]
6    CMP R3, #128        // compare R3 to 128
7    ADDGE R0, R0, R3    // if R3 >= 128, then sum += data[c] -- no branch needed!
8    ADD R1, R1, #1      // c++
9    CMP R1, #arraySize  // compare c to arraySize
10    BLT inner_loop      // Branch to inner_loop if c < arraySize
11
Full Screen
copy
1if (expression)
2{
3    // Run 1
4} else {
5    // Run 2
6}
7
Full Screen
copy
1 O      Route 1  /-------------------------------
2/|\             /
3 |  ---------##/
4/ \            \
5                \
6        Route 2  \--------------------------------
7
Full Screen
copy
1bool a, b, c, d;
2if (a != 0) {
3    if (b != 0) {
4        c = 1;
5    }
6    else {
7        goto CFALSE;
8    }
9}
10else {
11    CFALSE:
12    c = 0;
13}
14if (a == 0) {
15    if (b == 0) {
16        d = 0;
17    }
18    else {
19        goto DTRUE;
20    }
21}
22else {
23    DTRUE:
24    d = 1;
25}
26
Full Screen
copy
1char a = 0, b = 1, c, d;
2c = a & b;
3d = a | b;
4
Full Screen
copy
1bool a; double x, y, z;
2a = x > y && z < 5.0;
3
Full Screen
copy
1if (likely( everything_is_ok ))
2{
3    /* Do something */
4}
5
Full Screen
copy
1if (unlikely(very_improbable_condition))
2{
3    /* Do something */    
4}
5
Full Screen
copy
1                        A) if (data[c] >= 128)
2                                /\
3                               /  \
4                              /    \
5                        true /      \ false
6                            /        \
7                           /          \
8                          /            \
9                         /              \
10              B) sum += data[c];          C) for loop or print().
11
Full Screen
copy
1int i= 0, j, k= arraySize;
2while (i < k)
3{
4  j= (i + k) >> 1;
5  if (data[j] >= 128)
6    k= j;
7  else
8    i= j;
9}
10sum= 0;
11for (; i < arraySize; i++)
12  sum+= data[i];
13
Full Screen
copy
1int i, k, j= (i + k) >> 1;
2for (i= 0, k= arraySize; i < k; (data[j] >= 128 ? k : i)= j)
3  j= (i + k) >> 1;
4for (sum= 0; i < arraySize; i++)
5  sum+= data[i];
6
Full Screen
copy
1// Test
2clock_t start = clock();
3long long a[] = {0, 0};
4long long sum;
5
6for (unsigned i = 0; i < 100000; ++i)
7{
8    // Primary loop
9    for (unsigned c = 0; c < arraySize; ++c)
10    {
11        int j = (data[c] >> 7);
12        a[j] += data[c];
13    }
14}
15
16double elapsedTime = static_cast<double>(clock() - start) / CLOCKS_PER_SEC;
17sum = a[1];
18
Full Screen
copy
1// Declare and then fill in the lookup table
2int lut[256];
3for (unsigned c = 0; c < 256; ++c)
4    lut[c] = (c >= 128) ? c : 0;
5
6// Use the lookup table after it is built
7for (unsigned i = 0; i < 100000; ++i)
8{
9    // Primary loop
10    for (unsigned c = 0; c < arraySize; ++c)
11    {
12        sum += lut[data[c]];
13    }
14}
15
Full Screen
copy
1if (x < node->value)
2    node = node->pLeft;
3else
4    node = node->pRight;
5
Full Screen
copy
1i = (x < node->value);
2node = node->link[i];
3
Full Screen
copy
1for (int i = 0; i < max; i++)
2    if (condition)
3        sum++;
4
Full Screen
copy
1Condition                Pattern             Time (ms)
2-------------------------------------------------------
3(i & 0×80000000) == 0    T repeated          322
4
5(i & 0xffffffff) == 0    F repeated          276
6
7(i & 1) == 0             TF alternating      760
8
9(i & 3) == 0             TFFFTFFF…           513
10
11(i & 2) == 0             TTFFTTFF…           1675
12
13(i & 4) == 0             TTTTFFFFTTTTFFFF…   1275
14
15(i & 8) == 0             8T 8F 8T 8F …       752
16
17(i & 16) == 0            16T 16F 16T 16F …   490
18
Full Screen
copy
1for (int i = 0; i < array.Length; ++i)
2{
3   // Use array[i]
4}
5
Full Screen
copy
1// Generate data
2int arraySize = 32768;
3int[] data = new int[arraySize];
4
5Random random = new Random(0);
6for (int c = 0; c < arraySize; ++c)
7{
8    data[c] = random.Next(256);
9}
10
11/*To keep the spirit of the code intact, I'll make a separate lookup table
12(I assume we cannot modify 'data' or the number of loops)*/
13
14int[] lookup = new int[256];
15
16for (int c = 0; c < 256; ++c)
17{
18    lookup[c] = (c >= 128) ? c : 0;
19}
20
21// Test
22DateTime startTime = System.DateTime.Now;
23long sum = 0;
24
25for (int i = 0; i < 100000; ++i)
26{
27    // Primary loop
28    for (int j = 0; j < arraySize; ++j)
29    {
30        /* Here you basically want to use simple operations - so no
31        random branches, but things like &, |, *, -, +, etc. are fine. */
32        sum += lookup[data[j]];
33    }
34}
35
36DateTime endTime = System.DateTime.Now;
37Console.WriteLine(endTime - startTime);
38Console.WriteLine("sum = " + sum);
39Console.ReadLine();
40
Full Screen
copy
1==32551== Branches:        656,645,130  (  656,609,208 cond +    35,922 ind)
2==32551== Mispredicts:         169,556  (      169,095 cond +       461 ind)
3==32551== Mispred rate:            0.0% (          0.0%     +       1.2%   )
4
Full Screen
copy
1==32555== Branches:        655,996,082  (  655,960,160 cond +  35,922 ind)
2==32555== Mispredicts:     164,073,152  (  164,072,692 cond +     460 ind)
3==32555== Mispred rate:           25.0% (         25.0%     +     1.2%   )
4
Full Screen
copy
1          Bc    Bcm Bi Bim
2      10,001      4  0   0      for (unsigned i = 0; i < 10000; ++i)
3           .      .  .   .      {
4           .      .  .   .          // primary loop
5 327,690,000 10,016  0   0          for (unsigned c = 0; c < arraySize; ++c)
6           .      .  .   .          {
7 327,680,000 10,006  0   0              if (data[c] >= 128)
8           0      0  0   0                  sum += data[c];
9           .      .  .   .          }
10           .      .  .   .      }
11
Full Screen
copy
1          Bc         Bcm Bi Bim
2      10,001           4  0   0      for (unsigned i = 0; i < 10000; ++i)
3           .           .  .   .      {
4           .           .  .   .          // primary loop
5 327,690,000      10,038  0   0          for (unsigned c = 0; c < arraySize; ++c)
6           .           .  .   .          {
7 327,680,000 164,050,007  0   0              if (data[c] >= 128)
8           0           0  0   0                  sum += data[c];
9           .           .  .   .          }
10           .           .  .   .      }
11
Full Screen
copy
1 Performance counter stats for './sumtest_sorted':
2
3  11808.095776 task-clock                #    0.998 CPUs utilized          
4         1,062 context-switches          #    0.090 K/sec                  
5            14 CPU-migrations            #    0.001 K/sec                  
6           337 page-faults               #    0.029 K/sec                  
726,487,882,764 cycles                    #    2.243 GHz                    
841,025,654,322 instructions              #    1.55  insns per cycle        
9 6,558,871,379 branches                  #  555.455 M/sec                  
10       567,204 branch-misses             #    0.01% of all branches        
11
12  11.827228330 seconds time elapsed
13
Full Screen
copy
1 Performance counter stats for './sumtest_unsorted':
2
3  28877.954344 task-clock                #    0.998 CPUs utilized          
4         2,584 context-switches          #    0.089 K/sec                  
5            18 CPU-migrations            #    0.001 K/sec                  
6           335 page-faults               #    0.012 K/sec                  
765,076,127,595 cycles                    #    2.253 GHz                    
841,032,528,741 instructions              #    0.63  insns per cycle        
9 6,560,579,013 branches                  #  227.183 M/sec                  
10 1,646,394,749 branch-misses             #   25.10% of all branches        
11
12  28.935500947 seconds time elapsed
13
Full Screen
copy
1perf record -e branch-misses ./sumtest_unsorted
2perf annotate -d sumtest_unsorted
3
Full Screen
copy
1 Percent |      Source code & Disassembly of sumtest_unsorted
2------------------------------------------------
3...
4         :                      sum += data[c];
5    0.00 :        400a1a:       mov    -0x14(%rbp),%eax
6   39.97 :        400a1d:       mov    %eax,%eax
7    5.31 :        400a1f:       mov    -0x20040(%rbp,%rax,4),%eax
8    4.60 :        400a26:       cltq   
9    0.00 :        400a28:       add    %rax,-0x30(%rbp)
10...
11
Full Screen
copy
1for (unsigned i = 0; i < 100000; ++i)
2{
3    for (unsigned j = 0; j < arraySize; ++j)
4    {
5        if (data[j] >= 128)
6            sum += data[j];
7    }
8}
9
Full Screen
copy
1for (unsigned j = 0; j < arraySize; ++j)
2{
3    for (unsigned i = 0; i < 100000; ++i)
4    {
5        if (data[j] >= 128)
6            sum += data[j];
7    }
8}
9
Full Screen
copy
1for (unsigned j = 0; j < arraySize; ++j)
2{
3    if (data[j] >= 128)
4    {
5        for (unsigned i = 0; i < 100000; ++i)
6        {
7            sum += data[j];
8        }
9    }
10}
11
Full Screen
copy
1for (unsigned j = 0; j < arraySize; ++j)
2{
3    if (data[j] >= 128)
4    {
5        sum += data[j] * 100000;
6    }
7}
8
Full Screen
copy
1int max1(int a, int b) {
2    if (a > b)
3        return a;
4    else
5        return b;
6}
7
Full Screen
copy
1int max2(int a, int b) {
2    return a > b ? a : b;
3}
4
Full Screen
copy
1:max1
2    movl    %edi, -4(%rbp)
3    movl    %esi, -8(%rbp)
4    movl    -4(%rbp), %eax
5    cmpl    -8(%rbp), %eax
6    jle     .L2
7    movl    -4(%rbp), %eax
8    movl    %eax, -12(%rbp)
9    jmp     .L4
10.L2:
11    movl    -8(%rbp), %eax
12    movl    %eax, -12(%rbp)
13.L4:
14    movl    -12(%rbp), %eax
15    leave
16    ret
17
18:max2
19    movl    %edi, -4(%rbp)
20    movl    %esi, -8(%rbp)
21    movl    -4(%rbp), %eax
22    cmpl    %eax, -8(%rbp)
23    cmovge  -8(%rbp), %eax
24    leave
25    ret
26
Full Screen
copy
1T = branch taken
2N = branch not taken
3
4data[] = 0, 1, 2, 3, 4, ... 126, 127, 128, 129, 130, ... 250, 251, 252, ...
5branch = N  N  N  N  N  ...   N    N    T    T    T  ...   T    T    T  ...
6
7       = NNNNNNNNNNNN ... NNNNNNNTTTTTTTTT ... TTTTTTTTTT  (easy to predict)
8
Full Screen
copy
1data[] = 226, 185, 125, 158, 198, 144, 217, 79, 202, 118,  14, 150, 177, 182, ...
2branch =   T,   T,   N,   T,   T,   T,   T,  N,   T,   N,   N,   T,   T,   T  ...
3
4       = TTNTTTTNTNNTTT ...   (completely random - impossible to predict)
5
Full Screen
copy
1int t = (data[c] - 128) >> 31;
2sum += ~t & data[c];
3
Full Screen
copy
1String[] phrases = new String[10];
2String keyPhrase = "Bird";
3for(String phrase : phrases) {
4    System.out.println(phrase.equals(keyPhrase));
5}
6
Full Screen
copy
1String[] phrases = new String[] {"The bird", "A bird", "My bird", "Bird"};
2String keyPhrase = "Bird";
3for(String phrase : phrases) {
4    System.out.println(phrase.equals(keyPhrase));
5}
6
Full Screen
copy
1public class Some {
2    private int id;
3    public int getId(){
4        return this.id;
5    }
6    public setId( int newId ) {
7        this.id = newId;
8    }
9}
10
Full Screen
copy
1Some reference = new Some();    // Point to a new object of type Some()
2Some otherReference = null;     // Initiallly this points to NULL
3
4reference.setId( 1 );           // Execute setId method, now private var id is 1
5
6System.out.println( reference.getId() ); // Prints 1 to the console
7
8otherReference = reference      // Now they both point to the only object.
9
10reference = null;               // "reference" now point to null.
11
12// But "otherReference" still point to the "real" object so this print 1 too...
13System.out.println( otherReference.getId() );
14
15// Guess what will happen
16System.out.println( reference.getId() ); // :S Throws NullPointerException because "reference" is pointing to NULL remember...
17
Full Screen
copy
1public class Student {
2
3    private int id;
4
5    public int getId() {
6        return this.id;
7    }
8
9    public setId(int newId) {
10        this.id = newId;
11    }
12}
13
Full Screen
copy
1public class School {
2
3    Student student;
4
5    public School() {
6        try {
7            student.getId();
8        }
9        catch(Exception e) {
10            System.out.println("Null pointer exception");
11        }
12    }
13}
14
Full Screen
copy
1public class School {
2
3    Student student;
4
5    public School() {
6        try {
7            student = new Student();
8            student.setId(12);
9            student.getId();
10        }
11        catch(Exception e) {
12            System.out.println("Null pointer exception");
13        }
14    }
15}
16
Full Screen
copy
1String a = null;
2System.out.println(a.toString()); // NullPointerException will be thrown
3
Full Screen
copy
1public class Test {
2    public static void main(String[] args) {
3        String foo = null;
4        int length = foo.length();   // HERE
5    }
6}
7
Full Screen
copy
1$ javac Test.java 
2$ java Test
3Exception in thread "main" java.lang.NullPointerException
4    at Test.main(Test.java:4)
5$
6
Full Screen
copy
1Exception in thread "main" java.lang.NullPointerException
2
Full Screen
copy
1int length = foo.length(); // HERE
2
Full Screen
copy
1public class Test {
2
3    private static String[] foo = new String[2];
4
5    private static int test(String[] bar, int pos) {
6        return bar[pos].length();
7    }
8
9    public static void main(String[] args) {
10        int length = test(foo, 1);
11    }
12}
13
14$ javac Test.java 
15$ java Test
16Exception in thread "main" java.lang.NullPointerException
17    at Test.test(Test.java:6)
18    at Test.main(Test.java:10)
19$ 
20
Full Screen
copy
1int length = test(foo, 1);
2    
3
copy
1private static String[] foo = new String[2];
2
Full Screen
copy
1public class Printer {
2    private String name;
3
4    public void setName(String name) {
5        this.name = name;
6    }
7
8    public void print() {
9        printString(name);
10    }
11
12    private void printString(String s) {
13        System.out.println(s + " (" + s.length() + ")");
14    }
15
16    public static void main(String[] args) {
17        Printer printer = new Printer();
18        printer.print();
19    }
20}
21
Full Screen
copy
1Exception in thread "main" java.lang.NullPointerException
2    at Printer.printString(Printer.java:13)
3    at Printer.print(Printer.java:9)
4    at Printer.main(Printer.java:19)
5
Full Screen
copy
1printString((name == null) ? "" : name);
2
Full Screen
copy
1public class Printer {
2    private final String name;
3
4    public Printer(String name) {
5        this.name = Objects.requireNonNull(name);
6    }
7
8    public void print() {
9        printString(name);
10    }
11
12    private void printString(String s) {
13        System.out.println(s + " (" + s.length() + ")");
14    }
15
16    public static void main(String[] args) {
17        Printer printer = new Printer("123");
18        printer.print();
19    }
20}
21
Full Screen
copy
1public class Example {
2
3    public static void main(String[] args) {
4        Object obj = null;
5        obj.hashCode();
6    }
7
8}
9
Full Screen
copy
1Integer num;
2num = new Integer(10);
3
Full Screen
copy
1public void doSomething(SomeObject obj) {
2   // Do something to obj, assumes obj is not null
3   obj.myMethod();
4}
5
Full Screen
copy
1// Throws an NPE with a custom error message if obj is null
2Objects.requireNonNull(obj, "obj must not be null");
3
Full Screen
copy
1/**
2  * @param obj An optional foo for ____. May be null, in which case
3  *  the result will be ____.
4  */
5public void doSomething(SomeObject obj) {
6    if(obj == null) {
7       // Do something
8    } else {
9       // Do something else
10    }
11}
12
Full Screen
copy
1// CPP program to demonstrate processing
2// time of sorted and unsorted array
3#include <iostream>
4#include <algorithm>
5#include <ctime>
6using namespace std;
7
8const int N = 100001;
9
10int main()
11{
12    int arr[N];
13
14    // Assign random values to array
15    for (int i=0; i<N; i++)
16        arr[i] = rand()%N;
17
18    // for loop for unsorted array
19    int count = 0;
20    double start = clock();
21    for (int i=0; i<N; i++)
22        if (arr[i] < N/2)
23            count++;
24
25    double end = clock();
26    cout << "Time for unsorted array :: "
27        << ((end - start)/CLOCKS_PER_SEC)
28        << endl;
29    sort(arr, arr+N);
30
31    // for loop for sorted array
32    count = 0;
33    start = clock();
34
35    for (int i=0; i<N; i++)
36        if (arr[i] < N/2)
37            count++;
38
39    end = clock();
40    cout << "Time for sorted array :: "
41        << ((end - start)/CLOCKS_PER_SEC)
42        << endl;
43
44    return 0;
45}
46
Full Screen
copy
1Already sorted    32995 milliseconds
2Shuffled          125944 milliseconds
3
4Already sorted    18610 milliseconds
5Shuffled          133304 milliseconds
6
7Already sorted    17942 milliseconds
8Shuffled          107858 milliseconds
9
Full Screen
copy
1void run(vector<int>& v, const string& label)
2{
3    auto t0 = system_clock::now();
4    sort(v.begin(), v.end());
5    auto t1 = system_clock::now();
6    cout << label
7         << duration_cast<microseconds>(t1 — t0).count()
8         << " milliseconds\n";
9}
10
11void tst()
12{
13    vector<int> v(1'000'000);
14    iota(v.begin(), v.end(), 0);
15    run(v, "already sorted ");
16    std::shuffle(v.begin(), v.end(), std::mt19937{ std::random_device{}() });
17    run(v, "shuffled    ");
18}
19
Full Screen
copy
1#include <algorithm>
2#include <ctime>
3#include <iostream>
4
5int main() {
6    int data[32768]; const int l = sizeof data / sizeof data[0];
7
8    for (unsigned c = 0; c < l; ++c)
9        data[c] = std::rand() % 256;
10
11    // sort 200-element segments, not the whole array
12    for (unsigned c = 0; c + 200 <= l; c += 200)
13        std::sort(&data[c], &data[c + 200]);
14
15    clock_t start = clock();
16    long long sum = 0;
17
18    for (unsigned i = 0; i < 100000; ++i) {
19        for (unsigned c = 0; c < sizeof data / sizeof(int); ++c) {
20            if (data[c] >= 128)
21                sum += data[c];
22        }
23    }
24
25    std::cout << static_cast<double>(clock() - start) / CLOCKS_PER_SEC << std::endl;
26    std::cout << "sum = " << sum << std::endl;
27}
28
Full Screen
copy
1% Processing time with Sorted data vs unsorted data
2%==========================================================================
3% Generate data
4arraySize = 32768
5sum = 0;
6% Generate random integer data from range 0 to 255
7data = randi(256, arraySize, 1);
8
9
10%Sort the data
11data1= sort(data); % data1= data  when no sorting done
12
13
14%Start a stopwatch timer to measure the execution time
15tic;
16
17for i=1:100000
18
19    for j=1:arraySize
20
21        if data1(j)>=128
22            sum=sum + data1(j);
23        end
24    end
25end
26
27toc;
28
29ExeTimeWithSorting = toc - tic;
30
Full Screen
copy
1  a: Elapsed time (without sorting) = 3479.880861 seconds.
2  b: Elapsed time (with sorting ) = 2377.873098 seconds.
3
Full Screen
copy
1  a: Elapsed time (without sorting) = 19.8761 sec.
2  b: Elapsed time (with sorting ) = 7.37778 sec.
3
Full Screen
copy
1____________________________________________________________________________________
2- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT
4
Full Screen
copy
1___________________________________________ Straight road
2 |_________________________________________|Longer road
3
Full Screen
copy
1 // sort backwards (higher values first), may be in some other part of the code
2 std::sort(data, data + arraySize, std::greater<int>());
3
4 for (unsigned c = 0; c < arraySize; ++c) {
5       if (data[c] < 128) {
6              break;
7       }
8       sum += data[c];               
9 }
10
Full Screen
copy
1MOV R0, #0   // R0 = sum = 0
2MOV R1, #0   // R1 = c = 0
3ADR R2, data // R2 = addr of data array (put this instruction outside outer loop)
4.inner_loop  // Inner loop branch label
5    LDRB R3, [R2, R1]   // R3 = data[c]
6    CMP R3, #128        // compare R3 to 128
7    ADDGE R0, R0, R3    // if R3 >= 128, then sum += data[c] -- no branch needed!
8    ADD R1, R1, #1      // c++
9    CMP R1, #arraySize  // compare c to arraySize
10    BLT inner_loop      // Branch to inner_loop if c < arraySize
11
Full Screen
copy
1if (expression)
2{
3    // Run 1
4} else {
5    // Run 2
6}
7
Full Screen
copy
1 O      Route 1  /-------------------------------
2/|\             /
3 |  ---------##/
4/ \            \
5                \
6        Route 2  \--------------------------------
7
Full Screen
copy
1bool a, b, c, d;
2if (a != 0) {
3    if (b != 0) {
4        c = 1;
5    }
6    else {
7        goto CFALSE;
8    }
9}
10else {
11    CFALSE:
12    c = 0;
13}
14if (a == 0) {
15    if (b == 0) {
16        d = 0;
17    }
18    else {
19        goto DTRUE;
20    }
21}
22else {
23    DTRUE:
24    d = 1;
25}
26
Full Screen
copy
1char a = 0, b = 1, c, d;
2c = a & b;
3d = a | b;
4
Full Screen
copy
1bool a; double x, y, z;
2a = x > y && z < 5.0;
3
Full Screen
copy
1if (likely( everything_is_ok ))
2{
3    /* Do something */
4}
5
Full Screen
copy
1if (unlikely(very_improbable_condition))
2{
3    /* Do something */    
4}
5
Full Screen
copy
1                        A) if (data[c] >= 128)
2                                /\
3                               /  \
4                              /    \
5                        true /      \ false
6                            /        \
7                           /          \
8                          /            \
9                         /              \
10              B) sum += data[c];          C) for loop or print().
11
Full Screen
copy
1int i= 0, j, k= arraySize;
2while (i < k)
3{
4  j= (i + k) >> 1;
5  if (data[j] >= 128)
6    k= j;
7  else
8    i= j;
9}
10sum= 0;
11for (; i < arraySize; i++)
12  sum+= data[i];
13
Full Screen
copy
1int i, k, j= (i + k) >> 1;
2for (i= 0, k= arraySize; i < k; (data[j] >= 128 ? k : i)= j)
3  j= (i + k) >> 1;
4for (sum= 0; i < arraySize; i++)
5  sum+= data[i];
6
Full Screen
copy
1// Test
2clock_t start = clock();
3long long a[] = {0, 0};
4long long sum;
5
6for (unsigned i = 0; i < 100000; ++i)
7{
8    // Primary loop
9    for (unsigned c = 0; c < arraySize; ++c)
10    {
11        int j = (data[c] >> 7);
12        a[j] += data[c];
13    }
14}
15
16double elapsedTime = static_cast<double>(clock() - start) / CLOCKS_PER_SEC;
17sum = a[1];
18
Full Screen
copy
1// Declare and then fill in the lookup table
2int lut[256];
3for (unsigned c = 0; c < 256; ++c)
4    lut[c] = (c >= 128) ? c : 0;
5
6// Use the lookup table after it is built
7for (unsigned i = 0; i < 100000; ++i)
8{
9    // Primary loop
10    for (unsigned c = 0; c < arraySize; ++c)
11    {
12        sum += lut[data[c]];
13    }
14}
15
Full Screen
copy
1if (x < node->value)
2    node = node->pLeft;
3else
4    node = node->pRight;
5
Full Screen
copy
1i = (x < node->value);
2node = node->link[i];
3
Full Screen
copy
1for (int i = 0; i < max; i++)
2    if (condition)
3        sum++;
4
Full Screen
copy
1Condition                Pattern             Time (ms)
2-------------------------------------------------------
3(i & 0×80000000) == 0    T repeated          322
4
5(i & 0xffffffff) == 0    F repeated          276
6
7(i & 1) == 0             TF alternating      760
8
9(i & 3) == 0             TFFFTFFF…           513
10
11(i & 2) == 0             TTFFTTFF…           1675
12
13(i & 4) == 0             TTTTFFFFTTTTFFFF…   1275
14
15(i & 8) == 0             8T 8F 8T 8F …       752
16
17(i & 16) == 0            16T 16F 16T 16F …   490
18
Full Screen
copy
1for (int i = 0; i < array.Length; ++i)
2{
3   // Use array[i]
4}
5
Full Screen
copy
1// Generate data
2int arraySize = 32768;
3int[] data = new int[arraySize];
4
5Random random = new Random(0);
6for (int c = 0; c < arraySize; ++c)
7{
8    data[c] = random.Next(256);
9}
10
11/*To keep the spirit of the code intact, I'll make a separate lookup table
12(I assume we cannot modify 'data' or the number of loops)*/
13
14int[] lookup = new int[256];
15
16for (int c = 0; c < 256; ++c)
17{
18    lookup[c] = (c >= 128) ? c : 0;
19}
20
21// Test
22DateTime startTime = System.DateTime.Now;
23long sum = 0;
24
25for (int i = 0; i < 100000; ++i)
26{
27    // Primary loop
28    for (int j = 0; j < arraySize; ++j)
29    {
30        /* Here you basically want to use simple operations - so no
31        random branches, but things like &, |, *, -, +, etc. are fine. */
32        sum += lookup[data[j]];
33    }
34}
35
36DateTime endTime = System.DateTime.Now;
37Console.WriteLine(endTime - startTime);
38Console.WriteLine("sum = " + sum);
39Console.ReadLine();
40
Full Screen
copy
1==32551== Branches:        656,645,130  (  656,609,208 cond +    35,922 ind)
2==32551== Mispredicts:         169,556  (      169,095 cond +       461 ind)
3==32551== Mispred rate:            0.0% (          0.0%     +       1.2%   )
4
Full Screen
copy
1==32555== Branches:        655,996,082  (  655,960,160 cond +  35,922 ind)
2==32555== Mispredicts:     164,073,152  (  164,072,692 cond +     460 ind)
3==32555== Mispred rate:           25.0% (         25.0%     +     1.2%   )
4
Full Screen
copy
1          Bc    Bcm Bi Bim
2      10,001      4  0   0      for (unsigned i = 0; i < 10000; ++i)
3           .      .  .   .      {
4           .      .  .   .          // primary loop
5 327,690,000 10,016  0   0          for (unsigned c = 0; c < arraySize; ++c)
6           .      .  .   .          {
7 327,680,000 10,006  0   0              if (data[c] >= 128)
8           0      0  0   0                  sum += data[c];
9           .      .  .   .          }
10           .      .  .   .      }
11
Full Screen
copy
1          Bc         Bcm Bi Bim
2      10,001           4  0   0      for (unsigned i = 0; i < 10000; ++i)
3           .           .  .   .      {
4           .           .  .   .          // primary loop
5 327,690,000      10,038  0   0          for (unsigned c = 0; c < arraySize; ++c)
6           .           .  .   .          {
7 327,680,000 164,050,<