为什么许多小memcpy比一个大memcpy快?

时间:2018-05-07 15:57:51

标签: c++ memory memcpy

我发现拥有许多小内存比拥有一个大内存更快。我不明白为什么会这样。在复制大块数据时,memcpy不是更好吗?

我在VC ++ 2017和英特尔编译器2018上测试了以下代码。

一个大memcpy的时间:0.457913和许多小memcpy的时间:0.121063

typedef double tp;
size_t sz = 100;
size_t nm = 1000000;
tp* x = new tp[sz*nm];
std::vector<tp*> y(nm);
for (int i = 0; i < nm; ++i)
   y[i] = new tp[sz];

tp*  z1 = new tp[sz*nm];
std::vector<tp*> z2(nm);
for (int i = 0; i < nm; ++i)
   z2[i] = new tp[sz];

double currTime, lastTime;

lastTime = omp_get_wtime();
memcpy((void*)z1, (void*)x, sizeof(tp)*sz*nm);
currTime = omp_get_wtime();
std::cout << "time for one large memcpy: " << currTime - lastTime << std::endl;

lastTime = omp_get_wtime();
for (int i = 0; i < nm; ++i)
    memcpy((void*)z2[i], (void*)y[i], sizeof(tp)*sz);
currTime = omp_get_wtime();
std::cout << "time for many small memcpy: " << currTime - lastTime << std::endl;

delete[] x;
delete[] z1;
for (int i = 0; i < nm; ++i)
{
   delete[] y[i];
   delete[] z2[i];
}

0 个答案:

没有答案