-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfor-loop.cpp
More file actions
76 lines (54 loc) · 1.82 KB
/
for-loop.cpp
File metadata and controls
76 lines (54 loc) · 1.82 KB
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
// Copyright (c) 2019 Edwin Pratt
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
#include <iostream>
#include "../src/timer.h"
int main() {
/*
This is a test to compare the performance of various for loops against arrays.
The for loops which will be tested are:
* for (int i = 0; i < (int)(sizeof(array) / sizeof(array[0])); i++) {
sum += array[i];
}
* for (int i = 0, size = (int)(sizeof(array) / sizeof(array[0])); i < size; i++) {
sum += array[i];
}
* for (int i = 0, size = (int)(sizeof(array) / sizeof(array[0])); i < size; i += sizeof(array[0])) {
sum += *(array + i);
}
*/
// ===============
int array[1000];
for (int i = 0; i < 1000; i++) {
array[i] = i;
}
// ===============
std::cout << "Test 1: The size is computed every iteration of the loop, and standard array indexing is performed." << std::endl;
{
Timer t;
int sum = 0;
for (int i = 0; i < (int)(sizeof(array) / sizeof(array[0])); i++) {
sum += array[i];
}
}
std::cout << "\n";
std::cout << "Test 2: The size is stored in a variable, and standard array indexing is performed." << std::endl;
{
Timer t;
int sum = 0;
for (int i = 0, size = (int)(sizeof(array) / sizeof(array[0])); i < size; i++) {
sum += array[i];
}
}
std::cout << "\n";
std::cout << "Test 3: The size is stored in a variable, and the array is indexed as a pointer." << std::endl;
{
Timer t;
int sum = 0;
for (int i = 0, size = (int)(sizeof(array) / sizeof(array[0])); i < size; i += sizeof(array[0])) {
sum += *(array + i);
}
}
return 0;
}