I have been using MATLAB for some time for my projects, and I almost never had any experience with C ++.
I needed speed, and I heard that C ++ can be more efficient and faster than MATLAB. So I tried this:
I created a random number matrix using rand (5000,5000) on MATLAB.
And in C ++, I initialized a 2D vector created 2 for loops, each of which loops 5000 times each time. MATLAB was 4-5 times faster, so I thought it was because Matlab executes vectorized codes in parallel, then I wrote C ++ code using parallel_for. Here is the code:
#include "stdafx.h" #include <iostream> #include <vector> #include <fstream> #include <ppl.h> using namespace std; using namespace concurrency; int main(); { int a = 5000, b = 5000, j, k; vector< vector<int> > vec(a, vector<imt>(b)); parallel_for(int(0), a, [&](int i) { for (j = 0; j <b; j++) { vec[i][j] = rand(); } }); }
Thus, the code is about 25% faster than MATLAB rand(5000,5000) However, C ++ uses 100% of the processor, and MATLAB uses 30% of the CPU.
So I got MATLAB to use the whole processor by starting 3 instances of MATLAB using rand(5000,5000) and dividing the time it takes by 3. It made MATLAB twice as fast as C ++.
I wonder what I'm missing? I know this is a tiny example, but I need an answer to port my code to C ++.
Current state:
When I write C ++ code without parallel_for , I get half the MATLAB speed with the same CPU usage. However, the people who gave the answers say they are almost the same. I do not understand what I am missing
here is a snapshot of the optimization menu 