The following programs measures the time required to access an array 500000 time
ID: 3830429 • Letter: T
Question
The following programs measures the time required to access an array 500000 times using array indexing.
Rewrite the program so that your program accesses the array using pointer notation.
Execute both programs multiple times and compare execution times.
#include
using namespace std;
using namespace std::chrono;
void main()
{
int i, loop, ary[1000] = {};
double sum = 0.0;
__int64 duration;
high_resolution_clock::time_point t1, t2;
t1 = high_resolution_clock::now();
for (i = 0; i < 1000; i++)
ary[i] = 1;
for (loop = 0; loop < 500000; loop++)
{
for (i = 0; i < 1000; i++)
sum += ary[i];
}
cout << "sum = " << sum << endl;
t2 = high_resolution_clock::now();
duration = std::chrono::duration_cast(t2 - t1).count();
cout << duration << endl << endl;
} // main.
Explanation / Answer
Here is the pointer notation to access the array:
#include<iostream>
using namespace std;
using namespace std::chrono;
void main()
{
int i, loop, ary[1000] = {};
double sum = 0.0;
__int64 duration;
high_resolution_clock::time_point t1, t2;
t1 = high_resolution_clock::now();
for (i = 0; i < 1000; i++)
*(ary + i) = 1; //Accessing using pointer notation.
for (loop = 0; loop < 500000; loop++)
{
for (i = 0; i < 1000; i++)
sum += *(ary + i);
}
cout << "sum = " << sum << endl;
t2 = high_resolution_clock::now();
duration = std::chrono::duration_cast(t2 - t1).count();
cout << duration << endl << endl;
} // main.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.