-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbranch_prediction.cpp
68 lines (50 loc) · 1.6 KB
/
branch_prediction.cpp
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
/*
See the effect of branch prediction!
Sorted array takes an order of magnitude less to do conditional sum since the if(data[c]>=128) branch is much predictable then.
###############################################################################
Without sort, time ./a.out
###############################################################################
21.773
sum = 314931600000
real 0m21.799s
user 0m21.772s
sys 0m0.000s
###############################################################################
###############################################################################
With sort, time ./a.out
###############################################################################
7.91469
sum = 314931600000
real 0m7.925s
user 0m7.920s
sys 0m0.000s
###############################################################################
*/
#include <algorithm>
#include <ctime>
#include <iostream>
int main()
{
// Generate data
const unsigned arraySize = 32768;
int data[arraySize];
for (unsigned c = 0; c < arraySize; ++c)
data[c] = std::rand() % 256;
// !!! With this, the next loop runs faster
// std::sort(data, data + arraySize);
// Test
clock_t start = clock();
long long sum = 0;
for (unsigned i = 0; i < 100000; ++i)
{
// Primary loop
for (unsigned c = 0; c < arraySize; ++c)
{
if (data[c] >= 128)
sum += data[c];
}
}
double elapsedTime = static_cast<double>(clock() - start) / CLOCKS_PER_SEC;
std::cout << elapsedTime << std::endl;
std::cout << "sum = " << sum << std::endl;
}