mercredi 23 novembre 2016

Efficient way to return stl vectorby value from function

This is sort of an extension question from Efficient way to return a std::vector in c++

#include <cstdio>
#include <vector>
#include <chrono>

std::vector<int> func1() {
    std::vector<int> v;
    for (int i = 0; i < 1e6; i++) v.push_back(i);
    return v;
}

std::vector<int> func2() {
    std::vector<int> v;
    for (int i = 0; i < 1e6; i++) v.push_back(i);
    return std::move(v);
}

int main() {
    auto start1 = std::chrono::steady_clock::now();
    std::vector<int> v1 = func1();
    auto end1 = std::chrono::steady_clock::now();
    printf("%d\n", std::chrono::duration_cast<std::chrono::nanoseconds>(end1-start1).count());

    auto start2 = std::chrono::steady_clock::now();
    std::vector<int> v2 = func2();
    auto end2 = std::chrono::steady_clock::now();
    printf("%d\n", std::chrono::duration_cast<std::chrono::nanoseconds>(end2-start2).count());

    auto start3 = std::chrono::steady_clock::now();
    std::vector<int> v3 = v2;
    auto end3 = std::chrono::steady_clock::now();
    printf("%d\n", std::chrono::duration_cast<std::chrono::nanoseconds>(end3-start3).count());

    return 0;
}

In method 2, I explicitly tells the compiler I want to move instead of copy the vector, but running the code multiple times shows that method 1 actually outperform method 2 sometimes, and even if method 2 wins, it is not by much.

Method 3 is consistently the best. How to emulate method 3 when I must return from function? (No, I cannot pass by reference)

Using gcc 6.1.0

Aucun commentaire:

Enregistrer un commentaire