【问题标题】:memcpy byte rate per second [closed]每秒 memcpy 字节速率 [关闭]
【发布时间】:2013-06-15 11:45:44
【问题描述】:

memcpy 将 CPU 使用率提高到 100%,以便从缓冲区中复制每 10000 个元素。有什么方法可以优化 memcpy 以减少 CPU 使用率?

【问题讨论】:

  • 您需要以毫秒为单位的时间。 stackoverflow.com/questions/3756323/…
  • 您的程序不执行任何 I/O。如果它只消耗你 20% 的 CPU 时间,那么另外 80% 要么被浪费,要么被其他进程消耗。为什么这是一个目标?
  • 我被告知在我的程序中 CPU 使用率应至少为 20%。但是,当我运行程序并使用 htop 时,它显示 CPU 使用率为 60%。
  • @user1596226:如果您的 CPU 使用率应该是“最少 20%”(为什么?),那么 60% 就可以满足您的要求。更高的 CPU 使用率意味着您正在更有效地使用 CPU。另一方面,如果你编写一个循环复制一个字节并在每次迭代中休眠一秒钟,你可能会使你的 CPU 使用率低于 1%。

标签: c++ c linux memcpy


【解决方案1】:

(自此答案以来,该问题已完全重写)。

您的代码可以修改为在 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() 功能。

【讨论】:

    猜你喜欢
    • 2018-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多