0

After profiling my code, I noticed most time is in the do-while area of this snippet:

        uint16_t* vec=NULL; 
        double* data=NULL;
        double a,b;
        int len;
        size_t ret;

        // ... initialization/malloc as necessary

        ret = fread(vec, uint16_t, len, ptr);
        do {
            data[len-1] = ((double)vec[len-1])*a + b;
        } while (--len);

        // ... continue 

Is there any way to improve efficiency by elimination array indexing? In the C language, is it possible to do type conversion within fread? Hypothetically speaking, is there a way to work with this (completely incorrect pseudo code follows, but you get the idea...):

        ret = fread((double)data, uint16_t, len, ptr);
        do {
            data[len-1] *= a;
            data[len-1] += b;
        } while (--len);
Danlger
  • 143
  • 1
  • 1
  • 7
  • No it's not possible. For binary files `fread` will not do any kind of conversion, it will just read the raw data from the file into the memory you provide. – Some programmer dude Mar 27 '18 at 14:27
  • As for your problem, how often do you need to do this read/conversion? Do you need to read the whole file every time? – Some programmer dude Mar 27 '18 at 14:29
  • If the code is run on an architecture with hardware vectorization support (like x86-64), I would refactor the conversion to a helper function, and see if vectorizing the conversion by hand (via intrinsics) makes a difference. Note that both `vec` and `data` must be sufficiently aligned, then. – Nominal Animal Mar 27 '18 at 14:32
  • `a` and `b` are constants or variables? – freestyle Mar 27 '18 at 14:38
  • I'm not sure what you're asking. You ask about eliminating array indexing but then ask specifically about optimization in fread(), which you cannot modify. Since you're working with 16 bit quantities, alignment may offer improvement (i.e. align the u16 to the doubles). [See this SO article](https://stackoverflow.com/a/23369071/988207). Hardware Vectorization is new to me. It looks pretty cool. [See this SO](https://stackoverflow.com/a/1422181/988207). – Andrew Falanga Mar 27 '18 at 15:05
  • 1) yes, I must read the entire binary file every time, 2) variables a and b are constant inside the do-loop. I have to read what those values are from the binary file, and they are set before fread. – Danlger Mar 27 '18 at 15:10
  • I can't edit my first comment any longer. I nearly forgot, if you do try an alignment solution on the `uint16_t` array, you'll break how fread() writes data into that array. – Andrew Falanga Mar 27 '18 at 15:14
  • a compilable function would look like: `void so(uint16_t *vec, double *data, FILE *ptr, size_t i, double a, double b){ for(size_t j=0;j – technosaurus Mar 27 '18 at 15:18

0 Answers0