editing mat is so slow
```
void test1(Mat& img, Mat& out)
{
int element_nums = img.rows * img.cols;
float *ptr_img = img.ptr<float>(0);
float *ptr_out = out.ptr<float>(0);
for (int i = 0; i < element_nums; ++i){
ptr_out[i] = std::exp(ptr_img[i]);
}
};
void test2(Mat& img, Mat& out)
{
int element_nums = img.rows * img.cols;
float *ptr_img = img.ptr<float>(0);
float *ptr_out = out.ptr<float>(0);
for (int i = 0; i < element_nums; ++i){
ptr_out[i] = ptr_img[i];
}
};
void test3(Mat& img, Mat& out){
int element_nums = img.rows * img.cols;
float *ptr_img = img.ptr<float>(0);
float *ptr_out = out.ptr<float>(0);
float* temp = new float[img.rows * img.cols];
for (int i = 0; i < element_nums; ++i){
temp[i] = std::exp(ptr_img[i]*(-i));
}
};
int main(int argc, char* argv[])
{
clock_t start, stop;
Mat testInput = Mat::ones(4000,4000, CV_32FC1);
Mat out = Mat(testInput.size(), CV_32FC1);
start = clock();
test1(testInput, out);
stop = clock();
cout<<"test1: "<<(double)(stop - start)/CLOCKS_PER_SEC*1000<<"ms"<<endl;
start = clock();
test2(testInput, out);
stop = clock();
cout<<"test2: "<<(double)(stop - start)/CLOCKS_PER_SEC*1000<<"ms"<<endl;
start = clock();
test3(testInput, out);
stop = clock();
cout<<"test3: "<<(double)(stop - start)/CLOCKS_PER_SEC*1000<<"ms"<<endl;
}
test1: 221.924ms
test2: 17.146ms
test3: 0.001ms
open4.1 mac 1.4 GHz Intel Core i5
why is editing mat so low?
First, don't use
clock_t
. It measures the CPU ticks (operations), which is not the same than the elapsed time (as modern CPUs make several operations per clock cycle). Use the functions provided by the standardchrono
library.Thanks for your suggestion. But editing mat is still so slow.