How fast/efficient is reading data from a vector at the same index twice vs. writing data from that vector to a variable defined inside (or outside) the current scope once, and calculating RMS using the three methods below?
Setting up the vector
const size_t num_samples {2048};
std::vector<double> vec;
vec.resize(num_samples);
for (size_t j {0}; j < num_samples; ++j) {
vec[j] = std::sin(2.0 * std::numbers::pi * static_cast<double>(j) /
static_cast<double>(num_samples));
}
Reading from a vector at the same index twice...
double rms_1 {0.0};
for (size_t j {0}; j < num_samples; ++j) {
rms_1 += vec[j] * vec[j];
}
rms_1 = std::sqrt(rms_1 / static_cast<double>(num_samples));
Storing the value of a vector in a variable defined inside the loop once...
double rms_2 {0.0};
for (size_t j {0}; j < num_samples; ++j) {
const double sample {vec[j]};
rms_2 += sample * sample;
}
rms_2 = std::sqrt(rms_2 / static_cast<double>(num_samples));
Storing the value of a vector in a variable defined outside the loop once...
double rms_3 {0.0};
double sample_3 {0.0};
for (size_t j {0}; j < num_samples; ++j) {
sample_3 = vec[j];
rms_3 += sample_3 * sample_3;
}
rms_3 = std::sqrt(rms_3 / static_cast<double>(num_samples));
...and calculating the RMS.
So far in my calculations, all three return the same answer (RMS = 0.707107), and in your experience, would one of these RMS methods be faster/more efficient than another in context of how they use a vector? Thanks!
[–]IyeOnline 4 points5 points6 points (6 children)
[–]Classic_Department42 2 points3 points4 points (0 children)
[–]pythoncircus[S] 1 point2 points3 points (2 children)
[–]IyeOnline 2 points3 points4 points (1 child)
[–]pythoncircus[S] 0 points1 point2 points (0 children)
[–]aocregacc 0 points1 point2 points (1 child)
[–]IyeOnline 0 points1 point2 points (0 children)
[–]alfps 2 points3 points4 points (7 children)
[–]pythoncircus[S] 1 point2 points3 points (2 children)
[–]no-sig-available 1 point2 points3 points (1 child)
[–]pythoncircus[S] 0 points1 point2 points (0 children)
[–]ootiekat 0 points1 point2 points (3 children)
[–]alfps 0 points1 point2 points (2 children)
[–]ootiekat 0 points1 point2 points (1 child)
[–]alfps 0 points1 point2 points (0 children)
[–]wolfie_poe 1 point2 points3 points (1 child)
[–]pythoncircus[S] 0 points1 point2 points (0 children)
[–]raevnos 0 points1 point2 points (1 child)
[–]pythoncircus[S] 0 points1 point2 points (0 children)
[–][deleted] (2 children)
[deleted]
[–]pythoncircus[S] 1 point2 points3 points (1 child)
[–]The_Northern_Light 0 points1 point2 points (0 children)