私は、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ではコンパイルされなかったので間違っています)。
現在のサブルーチンの 1 つを次に示します。
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;
}