Skip to content

Instantly share code, notes, and snippets.

@munnellg
Created August 22, 2018 18:02
Show Gist options
  • Save munnellg/bb7e1eedf9a34e190980a38fe5854225 to your computer and use it in GitHub Desktop.
Save munnellg/bb7e1eedf9a34e190980a38fe5854225 to your computer and use it in GitHub Desktop.
strlen performance comparison by Rick Meyer
// Compile (on OSX/Linux) using:
// clang -o benchmark -std=c++11 -Ofast benchmark.cpp -lstdc++
// gcc -o benchmark -std=c++11 -O3 benchmark.cpp -lstdc++
#include <cstring>
#include <chrono>
#include <iostream>
#include <assert.h>
double currentTimeInSeconds()
{
using namespace std::chrono;
static const auto startOfTime = high_resolution_clock::now();
const auto now = high_resolution_clock::now();
const auto sec = duration_cast<duration<double>>(now - startOfTime);
return sec.count();
}
size_t myStrLen(const char* p)
{
auto q = p;
while(*q)
q++;
return q - p;
}
int main(int, const char* [])
{
constexpr size_t maxLen = 1024 * 1024 * 1024;
for(size_t len = 1; len < maxLen ; len *= 2) {
char* buffer = new char[len + 1];
for(size_t i=0; i<len; i++)
buffer[i] = 'a';
buffer[len] = 0;
//const auto numLoops = maxLen / len; // so approx constant time
const auto numLoops = 100;
const auto start = currentTimeInSeconds();
for (size_t i = 0; i < numLoops; ++i) {
buffer[i % len] = 'b'; // required so the compiler doesn't move strlen out of the loop.
assert(strlen(buffer) == len);
}
const auto mid = currentTimeInSeconds();
for (size_t i = 0; i < numLoops; ++i) {
buffer[i % len] = 'b'; // required so the compiler doesn't move strlen out of the loop.
assert(myStrLen(buffer) == len);
}
const auto end = currentTimeInSeconds();
const auto t1 = mid - start;
const auto t2 = end - mid;
std::cout << "len=" << len
<< ", strlen=" << t1 << " sec"
<< ", myStrLen=" << t2 << " sec"
<< ", ratio=" << t2/t1
<< std::endl;
delete [] buffer;
}
}
@Hritik14
Copy link

Hritik14 commented Sep 1, 2018

Can you explain buffer[i % len] = 'b';

@munnellg
Copy link
Author

munnellg commented Sep 2, 2018

If the buffer is not modified inside the loop then there is a chance that the compiler will realize that calling the string length functions multiple times will always produce the same result. If this happens, then the compiler might optimize the loop away which means that we won't be able to benchmark the functions. The line you have highlighted just writes the letter 'b' at different points in the string to prevent the compiler from optimizing the loop away.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment