jeudi 2 août 2018

How to efficiently move an array to a vector in C++?

I am working with a function which requires me to pass in an C-style array so it can be filled with data. However, the resulting array must be converted to a vector so it can be passed to another function that needs it. The vector constraint is hard, there's no getting around it. I could conceivably rework the other function so that it takes a vector, but I'd prefer not to if it can be done efficiently otherwise. Specifically, I would like there to be no copying of the data from the array to the vector if possible. As a minimal example, take the following program:

#include <iostream>
#include <algorithm>
#include <vector>
#include <chrono>

using namespace std::chrono;

static uint LENGTH = 10000000;


uint now() {
    return duration_cast<microseconds>
            (system_clock::now().time_since_epoch()).count();
}

void put_data_in_array(char *data) {
    std::cout << now() << " filling array\n";
    for (uint i = 0; i < LENGTH; i++) {
        data[i] = i;
    }
    std::cout << now() << " filled array\n";
}

int main () {
    std::cout << now() << " making array\n";
    char *array = new char[LENGTH];
    std::cout << now() << " made array\n";
    put_data_in_array(array);
    std::cout << now() << " function returned\n";
    std::vector<int64_t> v;
    std::move(array, array + LENGTH, std::back_inserter(v));
    std::cout << now() << " switched to vector\n";
  return 0;
}

which produces the following output:

1970760826 making array
1970760926 made array
1970760927 filling array
1970774417 filled array
1970774421 function returned
1970879936 switched to vector

meaning:

100 µs to allocate memory for the array
13490 µs to fill the array
105515 µs to move the array to a vector

Ideally, I would like the time to move the array to a vector to be very small. If possible I'd like to tell the vector to take ownership of the existing array. However, if the time to transfer it to a vector can be close (less than twice) the time it takes to fill the array, I will be happy.

Thanks for any help you can give.

Aucun commentaire:

Enregistrer un commentaire