There is a function which is getting maximum values of each period-length interval in array.
I am trying to optimize this function by performance.
void maximumsT(const std::vector<double> &src, size_t period, std::vector<double> &dst)
{
dst.resize(src.size());
for (size_t i = 1; i <= period; ++i) {
dst[i - 1] = *std::max_element(src.begin(), src.begin() + i);
}
for (size_t i = period; i <= src.size(); ++i) {
dst[i - 1] = *std::max_element(src.begin() + i - period, src.begin() + i);
}
}
I asked this SO question
and got this solution.
Then I tried to implement the solution.
#include <vector>
#include <deque>
#include <algorithm>
void maximumsT(const std::vector<double> &src, size_t period, std::vector<double> &dst)
{
dst.resize(src.size());
for (size_t i = 1; i <= period; ++i) {
dst[i - 1] = *std::max_element(src.begin(), src.begin() + i);
}
for (size_t i = period; i <= src.size(); ++i) {
dst[i - 1] = *std::max_element(src.begin() + i - period, src.begin() + i);
}
}
void maximums(const std::vector<double> &src, size_t period, std::vector<double> &dst)
{
dst.resize(src.size());
std::deque<std::pair<size_t, double>> deq;
for (size_t i = 0; i < src.size(); ++i) {
if (!deq.empty() && i >= period && deq.front().first <= i - period) {
deq.pop_front();
}
while (!deq.empty() && deq.back().second < src[i]) {
deq.pop_back();
}
deq.push_back(std::make_pair(i, src[i]));
dst[i] = deq.front().second;
}
}
bool test()
{
std::vector<double> v(1 + rand() % 1000);
for (double &e : v) {
e = (double)rand() / RAND_MAX;
}
size_t period = 1 + (rand() % v.size());
std::vector<double> vv, vvv;
maximumsT(v, period, vv);
maximums (v, period, vvv);
return vv == vvv;
}
bool test(size_t iterations)
{
for (size_t i = 0; i < iterations; ++i) {
if (!test()) {
return false;
}
}
return true;
}
int main(int argc, char *argv[])
{
return test(10000);
}
How can I improve and optimize this code?
very muchis not a quantifiable amount. \$\endgroup\$