Trying to work with c++ to write faster code than Matlab, and will regularly want to get an array from a function. Decided that the easiest way to code this would be to create an array to fill with the answer I want, pass the pointer to the function, then let the function fill it with the answer. In this example, I've just made the function change all of the components to some number i.
The c++ code is
#include <iostream>
using namespace std;
void test2(int *change,int n, int i) //takes an array of n items and changes it to an array of n copies of i
{
for(int counter = 0; counter < n; ++counter)
*(change+counter) = i;
return;
}
int main()
{
int n = 5;
int i = 3;
int butts2[n];
for(int counter = 0; counter < n; ++counter)
butts2[counter] = counter;
for(int counter = 0; counter < n; ++counter)
cout << butts2[counter] << endl;
test2(butts2,n,i);
for(int counter = 0; counter < n; ++counter)
cout << butts2[counter] << endl;
return 0;
}
The matlab code is
tic
n = 5; i = 3;
butts = zeros(n,1);
for count = 1:n
butts(count) = count;
end
for count = 1:n
disp(butts(count));
end
for count = 1:n
butts(count)=i;
end
for count = 1:n
disp(butts(count));
end
time = toc
I expected the c++ code to outperform the matlab code, but in fact the c++ code takes about 0.03s but the matlab code takes about a tenth of that time. That the matlab code is faster when I comment out the displays in each code, and for larger values of n. What is taking the extra time in the c++ code?