In: Computer Science
C++
Build a struct with many data members inside (for example, a large array). Design any function that processes the data inside the struct (e.g. adding a few values together and returning the sum.) Write two versions of this function, one that passes by value and one that passes a const reference. Measure the time required to call each function 10,000 times.
C++ code:
#include<iostream>
#include<ctime>
using namespace std;
#define MAX 32000
struct number
{
int arr[MAX];
};
int sum1(struct number s1)
{
int total=0;
for(int i=0;i<MAX;i++)
{
total+=s1.arr[i];
}
return(total);
}
int sum2(const struct number& s2)
{
int total=0;
for(int i=0;i<MAX;i++)
{
total+=s2.arr[i];
}
return(total);
}
int main()
{
struct number s;
const int CLOCKS_PER_MS=CLOCKS_PER_SEC/1000;
for(int i=0;i<MAX;i++)
{
s.arr[i]=i;
}
clock_t start1=clock();
for(int j=0;j<10000;j++)//call using pass by
value
{
int sm1=sum1(s);
}
clock_t end1=clock();
clock_t start2=clock();
for(int j=0;j<10000;j++)////call using pass by
reference
{
int sm2=sum2(s);
}
clock_t end2=clock();
int time1=(end1-start1)/CLOCKS_PER_MS;//calculate time
for pass by value
int time2=(end2-start2)/CLOCKS_PER_MS;//calculate time
for pass by reference
cout<<"Time using pass by value:
"<<time1<<endl;
cout<<"Time using pass by constant reference:
"<<time2<<endl;
}
output: