linux memcpy 效率,memcpy每秒字节速率

(这个问题已经完全改写,因为这个答案)。

你的代码可以如下改变在Linux上运行:

#include

#include

#include

#include

const size_t NUM_ELEMENTS = 2*1024 * 1024;

const size_t ITERATIONS = 10000;

int main(int argc, char *argv[])

{

struct timespec start, stop;

unsigned short * src = (unsigned short *) malloc(sizeof(unsigned short) * NUM_ELEMENTS);

unsigned short * dest = (unsigned short *) malloc(sizeof(unsigned short) * NUM_ELEMENTS);

for(int ctr = 0; ctr < NUM_ELEMENTS; ctr++)

{

src[ctr] = rand();

}

clock_gettime(CLOCK_MONOTONIC, &start);

for(int iter = 0; iter < ITERATIONS; iter++){

memcpy(dest, src, NUM_ELEMENTS * sizeof(unsigned short));

}

clock_gettime(CLOCK_MONOTONIC, &stop);

double duration_d = (double)(stop.tv_sec - start.tv_sec) + (stop.tv_nsec - start.tv_nsec)/1000000000.0;

double bytes_sec = (ITERATIONS * (NUM_ELEMENTS/1024/1024) * sizeof(unsigned short))/duration_d;

printf("Duration: %.5lfs for %d iterations, %.3lfMB/sec ", duration_d, ITERATIONS, bytes_sec);

free(src);

free(dest);

return 0;

}

您可能需要-lrt链接来获得clock_gettime()功能。

(这个问题已经完全改写,因为这个答案)。 你的代码可以如下改变在Linux上运行: #include #include #include #include const size_t NUM_ELEMENTS = 2*1024 * 1024; const size_t ITERATIONS = 10000; int main(int argc, char *argv[]) { struct timespec start, stop; unsigned short * src = (unsigned short *) malloc(sizeof(unsigned short) * NUM_ELEMENTS); unsigned short * dest = (unsigned short *) malloc(sizeof(unsigned short) * NUM_ELEMENTS); for(int ctr = 0; ctr < NUM_ELEMENTS; ctr++) { src[ctr] = rand(); } clock_gettime(CLOCK_MONOTONIC, &start); for(int iter = 0; iter < ITERATIONS; iter++){ memcpy(dest, src, NUM_ELEMENTS * sizeof(unsigned short)); } clock_gettime(CLOCK_MONOTONIC, &stop); double duration_d = (double)(stop.tv_sec - start.tv_sec) + (stop.tv_nsec - start.tv_nsec)/1000000000.0; double bytes_sec = (ITERATIONS * (NUM_ELEMENTS/1024/1024) * sizeof(unsigned short))/duration_d; printf("Duration: %.5lfs for %d iterations, %.3lfMB/sec ", duration_d, ITERATIONS, bytes_sec); free(src); free(dest); return 0; } 您可能需要-lrt链接来获得clock_gettime()功能。
经验分享 程序员 微信小程序 职场和发展