How to initialize all members of an array to the same value?

后端 未结 23 1893
清歌不尽
清歌不尽 2020-11-21 04:34

I have a large array in C (not C++ if that makes a difference). I want to initialize all members of the same value.

I could swear I

23条回答
  •  悲哀的现实
    2020-11-21 05:26

    There is a fast way to initialize array of any type with given value. It works very well with large arrays. Algorithm is as follows:

    • initialize first element of the array (usual way)
    • copy part which has been set into part which has not been set, doubling the size with each next copy operation

    For 1 000 000 elements int array it is 4 times faster than regular loop initialization (i5, 2 cores, 2.3 GHz, 4GiB memory, 64 bits):

    loop runtime 0.004248 [seconds]

    memfill() runtime 0.001085 [seconds]


    #include 
    #include 
    #include 
    #define ARR_SIZE 1000000
    
    void memfill(void *dest, size_t destsize, size_t elemsize) {
       char   *nextdest = (char *) dest + elemsize;
       size_t movesize, donesize = elemsize;
    
       destsize -= elemsize;
       while (destsize) {
          movesize = (donesize < destsize) ? donesize : destsize;
          memcpy(nextdest, dest, movesize);
          nextdest += movesize; destsize -= movesize; donesize += movesize;
       }
    }    
    int main() {
        clock_t timeStart;
        double  runTime;
        int     i, a[ARR_SIZE];
    
        timeStart = clock();
        for (i = 0; i < ARR_SIZE; i++)
            a[i] = 9;    
        runTime = (double)(clock() - timeStart) / (double)CLOCKS_PER_SEC;
        printf("loop runtime %f [seconds]\n",runTime);
    
        timeStart = clock();
        a[0] = 10;
        memfill(a, sizeof(a), sizeof(a[0]));
        runTime = (double)(clock() - timeStart) / (double)CLOCKS_PER_SEC;
        printf("memfill() runtime %f [seconds]\n",runTime);
        return 0;
    }
    

提交回复
热议问题