Skip to content

Instantly share code, notes, and snippets.

@retorillo
Last active July 27, 2018 15:18
Show Gist options
  • Save retorillo/83f07a49030f49812e9217f488e40071 to your computer and use it in GitHub Desktop.
Save retorillo/83f07a49030f49812e9217f488e40071 to your computer and use it in GitHub Desktop.
Fast vector generation (>= C++11)
#include <string>
#include <vector>
void main() {
std::string foo = "baz";
std::vector<char> bar;
printf("%d\n", bar.capacity());
bar.resize(foo.size());
// CAUTION: vector::reserve affects only "capacity", so does not change its "size",
// will causes empty-like behavior if using for(:) loop, vector::resize is adequate.
// bar.reserve(foo.size());
printf("%d\n", bar.capacity());
// vector::reserve() and memcopy(vector::data(), ...) will be faster
// than push_back for-loop, if not data conversion is not required.
memcpy(bar.data(), foo.data(), foo.size());
printf("bar: %x %x %x \n", bar[0], bar[1], bar[2]);
printf("foo: %x %x %x \n", foo[0], foo[1], foo[2]);
}
// RESULT:
// 0
// 3
// bar: 62 61 7a
// foo: 62 61 7a
#include <string>
#include <vector>
#include <chrono>
std::vector<char> fast(std::string data);
std::vector<char> slow(std::string data);
void main() {
std::string data = "The quick brown fox jumps over the lazy dog.";
const char* unit = "microseconds";
const int e6 = 1000000;
std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
for (int c = 0; c < e6; c++)
slow(data);
std::chrono::duration<double> d1 = std::chrono::high_resolution_clock::now() - t1;
std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now();
for (int c = 0; c < e6; c++)
fast(data);
std::chrono::duration<double> d2 = std::chrono::high_resolution_clock::now() - t2;
printf("SLOW: %f %s\nFAST: %f %s\n", d1.count(), unit, d2.count(), unit);
}
// ** FAST METHOD IS 10-TIMES FASTER **
// SLOW: 5.445815 microseconds
// FAST: 0.549105 microseconds
std::vector<char> fast(std::string data) {
std::vector<char> v;
v.resize(data.length());
memcpy(v.data(), data.data(), data.size());
return v;
}
std::vector<char> slow(std::string data) {
std::vector<char> v;
for (int c = 0, l = data.length(); c < l; c++)
v.push_back(data[c]);
return v;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment