Last active
August 29, 2015 14:24
-
-
Save gyulalaszlo/e7bcd86e46ea06e336d5 to your computer and use it in GitHub Desktop.
Comparison of in-place vs return-by-value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This is a bad comparison as the data gets written back to the source array, | |
// so in-place has an advantage here. | |
// Compile with | |
// | |
// clang++ --std=c++11 -stdlib=libstdc++ -static -lstdc++ test.cpp | |
// On my machine it prints: | |
// When running unoptimized: | |
// | |
// finished generating data | |
// finished Normal in: 32193ms | |
// finished Inline in: 25776ms | |
// With -O2 | |
// | |
// finished generating data | |
// finished Normal in: 6875ms | |
// finished Inline in: 3042ms | |
#include <algorithm> | |
#include <vector> | |
#include <iostream> | |
#include <chrono> | |
#include <ctime> | |
std::string gen_random(const int len) { | |
static const char alphanum[] = | |
"0123456789" | |
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" | |
"abcdefghijklmnopqrstuvwxyz" | |
" /_."; | |
auto s = std::string{}; | |
s.resize(len); | |
for (int i = 0; i < len; ++i) { | |
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)]; | |
} | |
return s; | |
} | |
void preallocate(size_t n, std::vector<std::string>& out ) { | |
out.reserve(n); | |
for(size_t i=0; i < n; ++i) { | |
out.emplace_back(gen_random(20)); | |
} | |
} | |
std::string sanitize_filename(std::string filename) | |
{ | |
using std::begin; | |
using std::end; | |
std::replace(begin(filename), end(filename), '/', '_'); | |
return filename; | |
} | |
void sanitize(std::string& filename) | |
{ | |
using std::begin; | |
using std::end; | |
std::replace(begin(filename), end(filename), '/', '_'); | |
} | |
template <class Pred> | |
void run_with_time(const std::string& text, Pred pred) { | |
auto start = std::chrono::system_clock::now(); | |
pred(); | |
auto end = std::chrono::system_clock::now(); | |
auto elapsed_seconds = std::chrono::duration_cast<std::chrono::microseconds>( end - start ); | |
std::cout << "finished " << text | |
<< " in: " << elapsed_seconds.count() << "ms\n"; | |
} | |
int main() | |
{ | |
const auto example_count = 100000; | |
auto srcVec = std::vector<std::string>{}; | |
preallocate(example_count, srcVec); | |
auto src2Vec = std::vector<std::string>{}; | |
preallocate(example_count, src2Vec); | |
std::cout << "finished generating data\n"; | |
run_with_time( "Normal", [&](){ | |
for (auto& el : srcVec) { | |
el = sanitize_filename(el); | |
} | |
}); | |
run_with_time( "in-place", [&](){ | |
for (auto& el : src2Vec) { | |
sanitize(el); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment