memcpy每秒字节速率

时间:2013-06-19 04:19:51

标签: c++ c linux memcpy

memcpy将CPU使用率从缓冲区中复制每10000个元素增加到100%。有没有办法优化memcpy,以便它会降低CPU使用率?

1 个答案:

答案 0 :(得分:3)

(自从这个答案以来,这个问题已被完全改写)。

您的代码可以更改为在Linux上运行,如下所示:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

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\n", duration_d, ITERATIONS, bytes_sec);

    free(src);
    free(dest);

    return 0;
}

您可能需要与-lrt关联才能获得clock_gettime()功能。