The following program measures the time required to access an array 500000 times
ID: 3830088 • Letter: T
Question
The following program 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.
Assess the results with your own words in less than 100 words.
#include<iostream>
#include<chrono>
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<std::chrono::microseconds>(t2 - t1).count();
cout << duration << endl << endl;
} // main.
Explanation / Answer
#include<iostream>
#include<chrono>
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<std::chrono::microseconds>(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.