我正在努力尝试加快 C 中的一些一般数据处理。我编写了几个形式的子例程:
double *do_something(double *arr_in, ...) {
double *arr_out;
arr_out = malloc(...)
for (...) {
do the something on arr_in and put into arr_out
}
return arr_out;
}
我喜欢这种风格,因为它易于阅读和使用,但我通常将其称为:
array = do_something(array,...);
如果我改为使用 void 子函数作为:
void do_something(double *arr_in, ...) {
for (...) {
arr_in = do that something;
}
return;
}
更新1:我在可执行文件上运行了 valgrind --leak-check=full ,使用第一种方法似乎没有内存泄漏。但是,可执行文件链接到包含我使用此表单创建的所有子例程的库,因此它可能无法捕获库中的泄漏。
我很好奇我将如何编写包装器来释放内存以及 ** 的真正作用,或者指向指针的指针是什么,所以我避免使用 ** 路由(也许我做到了错误,因为它没有在我的 Mac 上编译)。
这是一个当前的子程序:
double *cos_taper(double *arr_in, int npts)
{
int i;
double *arr_out;
double cos_taper[npts];
int M;
M = floor( ((npts - 2) / 10) + .5);
arr_out = malloc(npts*sizeof(arr_out));
for (i=0; i<npts; i++) {
if (i<M) {
cos_taper[i] = .5 * (1-cos(i * PI / (M + 1)));
}
else if (i<npts - M - 2) {
cos_taper[i] = 1;
}
else if (i<npts) {
cos_taper[i] = .5 * (1-cos((npts - i - 1) * PI / (M + 1)));
}
arr_out[i] = arr_in[i] * cos_taper[i];
}
return arr_out;
}
根据我在这里得到的建议,听起来更好的方法是:
void *cos_taper(double *arr_in, double *arr_out, int npts)
{
int i;
double cos_taper[npts];
int M;
M = floor( ((npts - 2) / 10) + .5);
for (i=0; i<npts; i++) {
if (i<M) {
cos_taper[i] = .5 * (1-cos(i * PI / (M + 1)));
}
else if (i<npts - M - 2) {
cos_taper[i] = 1;
}
else if (i<npts) {
cos_taper[i] = .5 * (1-cos((npts - i - 1) * PI / (M + 1)));
}
arr_out[i] = arr_in[i] * cos_taper[i];
}
return
}
称呼:
int main() {
int npts;
double *data, *cos_tapered;
data = malloc(sizeof(data) * npts);
cos_tapered = malloc(sizeof(cos_tapered) * npts);
//fill data
cos_taper(data, cos_tapered, npts);
free(data);
...
free(cos_tapered);
...
return 0;
}