views:

154

answers:

4

What's this easiest / most efficient way to initialize these blocks of doubles, preferably at compile time:

#define N 1000
double mul1[N][N] __attribute__ ((aligned (64)));
double mul2[N][N] __attribute__ ((aligned (64)));

They're used for "const" read only test data.

+3  A: 

Static array initialisation (which I take it is what you want) is ALWAYS performed at compile time, so you initialise them as you would any other array.

anon
I figured that is what I need to do. I'm wondering if there is any way to statically init it all to one value without having to explicitly put a 1000x1000 array in my file. Kinda like a compile time memset for doubles.
Robert S. Barnes
A: 

If you need this for only this two arrays I prefer to generate a file filled with the default value from the make file.

If you need something more complicated, you can use Boost.Preprocessor library. You may use BOOST_PP_WHILE and BOOST_PP_ARRAY_PUSH_FRONT.

I think it will work :)

Yousf
+4  A: 

There is a GCC (not standard C!) feature called Designated Initializers

For 1D array it would be just:

double array[N] = {[0 ... (N-1)] = MY_DOUBLE_VALUE};

For 2D a bit trickier:

double array[N][N] = { [0 ... (N-1)] = {[0 ... (N-1)] = MY_DOUBLE_VALUE}};
qrdl
Exactly what I was looking for. But I'm having a problem that the above syntax doesn't seem to like the `__attribute__ ((aligned (64)));` I get a syntax error trying to use them together.
Robert S. Barnes
@Robert Hmm, it works for me: `double array[N][N] __attribute__ ((aligned(64))) = { [0 ... (N-1)] = {[0 ... (N-1)] = MY_DOUBLE_VALUE}};` I use GCC 4.2.1.
qrdl
@qrdl: Ahhh, I put the attribute in the wrong place - after the init code.
Robert S. Barnes
+1  A: 

Easiest and most efficient are sometimes incompatible. How efficient does it need to be?

Easiest is a loop. Are a million assignments in a simple loop really too slow for your purposes?

int i, j;
for (i = 0; i < N; ++i) {
  for (j = 0; j < N; ++j) {
    mul1[i][j] = INITIAL_VALUE_1;
    mul2[i][j] = INITIAL_VALUE_2;
  }
}

Have you timed the simple solution to see if it's fast enough? If not, how much faster does it need to be?

Adrian McCarthy
It may actually be quicker to initialize it at run time. With qrdl's solution I end up with a 16MB executable which probably takes longer to read off disk than what it would take to init at run time. However, the point of this question was more about wanting to know 1. if it could be done, and 2. how to do it. Now that I've seen how to do it I'll probably just init at run time.
Robert S. Barnes
I think Adrian made a point. I do not know in what scenario one may want to initialize an array quickly. In comparison to other part of code, time spent on the array initialization is negligible.
@lh3: I know, I know - I was just curious if it could be done in a memset style way at compile time.
Robert S. Barnes