【问题标题】:Replace the two malloc calls by allocating a single buffer and setting list1 and list2 by pointing into that buffer通过分配单个缓冲区并通过指向该缓冲区来设置 list1 和 list2 来替换两个 malloc 调用
【发布时间】:2021-07-19 19:22:33
【问题描述】:

我正在使用合并排序函数,它包含两个使用 malloc 函数的列表。为了提高性能,我需要通过分配单个缓冲区并设置 list1 来替换两个 malloc 调用 和list2 通过指向该缓冲区。这将 malloc/free 的调用次数减少了一半。

intType* list1 = (intType*)malloc(n1*sizeof(intType));
intType* list2 = (intType*)malloc(n2*sizeof(intType));

n1 = N /2; 和n2 = N -2;

N 是要排序的元素个数。

我尝试了不同的方法,但没有成功。有人可以帮忙吗?

【问题讨论】:

  • "and n2 = N -2;":你的意思是“and n2 = N - n1;”吗?
  • 是的,我很抱歉。它的 n2 = N -n1;

标签: c performance optimization buffer


【解决方案1】:

你可以这样做:

/* allocate buffer for the two arrays */
intType* list1 = malloc((n1 + n2) * sizeof(intType));
/* assign pointer with offset */
intType* list2 = list1 + n1;

/* some works */

free(list1);

还要注意malloc() family 的转换结果是considered as a bad practice。

【讨论】:

  • 小记,这只有在两种类型相同的情况下才能轻松实现。如果 2 个列表有不同的对齐要求,则可能必须添加额外的填充以确保第二个列表正确对齐。
  • @SalmanKhan 因为答案解决了您的问题,请接受它 - 请参阅What should I do when someone answers my question?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-09
  • 2021-07-21
相关资源
最近更新 更多