Skip to main content
edited tags
Link
200_success
  • 144.2k
  • 22
  • 188
  • 473
Tweeted twitter.com/#!/StackCodeReview/status/150945359944884224
Source Link
OlivierB
  • 71
  • 1
  • 1
  • 3

Vectors assignations and operations in a loop and parallelization with OpenMP

I use this piece of code to compute a short-time Fourier transform:

// Output pre-allocation
std::vector<std::vector<std::complex<T> > > y(nFft, std::vector<std::complex<T> >(nFrames, 0.0));

std::vector<T> xt;
std::vector<std::complex<T> > yt;
xt.reserve(nFft);
yt.reserve(nFft);

#pragma omp parallel for private(xt,yt)
for (unsigned int t = 0; t < nFrames; ++t) {
    const int offset = -((int) wSize/2) + t*nHop;

    // Extract frame of input data
    if (offset < 0) {
        xt.assign(x.begin(), x.begin() + offset + wSize);
        xt.resize(wSize, 0.0);
    }
    else if (offset + wSize > n) {
        xt.assign(x.begin() + offset, x.end());
        xt.resize(wSize, 0.0);
    }
    else
        xt.assign(x.begin() + offset, x.begin() + offset + wSize);

    // Apply window to current frame
    std::transform(xt.begin(), xt.end(), w.begin(), xt.begin(), std::multiplies<T>());

    // Zero padding
    std::rotate(xt.begin(), xt.begin() + wSize/2, xt.end());
    xt.insert(xt.begin() + wSize/2, nFft - wSize, 0.0);

    yt = fft(xt);  // Perform the FFT!

    #pragma omp critical
    {
        for (unsigned int f = 0; f < nFft; ++f)
            y[f][t] = yt[f];
    }
}

Is there something that I can improve, either in design style or performances, without sacrificing readability? Of course the point is to improve my coding skills without using any external library!

Regarding the xt and yt vectors, I put them outside the loop to improve the performances in mono-threaded (when OpenMP is disabled). In multi-threaded, there are copied for each thread anyway (hence the use of the private close).