Skip to content

Instantly share code, notes, and snippets.

@airekans
Last active August 29, 2015 14:12
Show Gist options
  • Save airekans/8d09ee71e120866d7c64 to your computer and use it in GitHub Desktop.
Save airekans/8d09ee71e120866d7c64 to your computer and use it in GitHub Desktop.
Performance comparison of various printf implementations
#include <sys/time.h>
#include <sstream>
#include <iostream>
#include <string>
#include <wx/string.h>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
using namespace std;
namespace {
unsigned int GetCurrentTime()
{
struct timeval now;
gettimeofday(&now, NULL);
unsigned int now_in_ms = now.tv_sec;
now_in_ms = now_in_ms * 1000 + now.tv_usec / 1000;
return now_in_ms;
}
class BenckmarkObject
{
const string m_output_prefix;
unsigned int m_begin_time;
public:
explicit BenckmarkObject(const string& output_prefix = "")
: m_output_prefix(output_prefix)
{
m_begin_time = GetCurrentTime();
}
~BenckmarkObject()
{
const unsigned int end_time = GetCurrentTime();
cout << m_output_prefix << " total runtime: " << end_time - m_begin_time << endl;
}
};
} // namespace
int main()
{
// do performance comparison
static const double test_double = 123.0234124;
static const char* expected_str = "123.0234";
static const int test_times = 1000000;
// wxString::Format
{
BenckmarkObject bench_obj("wxString::Format");
for (int i = 0; i < test_times; ++i)
{
(void) wxString::Format(wxT("%.4lf"), test_double);
}
assert(wxString::Format(wxT("%.4lf"), test_double) == expected_str);
}
{
ostringstream oss;
oss << std::fixed;
oss.precision(4);
BenckmarkObject bench_obj("ostringstream");
for (int i = 0; i < test_times; ++i)
{
oss << test_double;
wxString result(oss.str().c_str());
oss.str("");
}
oss << test_double;
assert(oss.str() == expected_str);
}
{
BenckmarkObject bench_obj("boost::format");
for (int i = 0; i < test_times; ++i)
{
(void) boost::str(boost::format("%.4lf") % test_double);
}
assert(boost::str(boost::format("%.4lf") % test_double) == expected_str);
}
{
BenckmarkObject bench_obj("boost::lexical_cast");
for (int i = 0; i < test_times; ++i)
{
(void) boost::lexical_cast<string>(test_double);
}
//assert(boost::lexical_cast<string>(test_double) == expected_str);
}
{
static char double_buff[1024] = {'\0'};
BenckmarkObject bench_obj("snprintf");
for (int i = 0; i < test_times; ++i)
{
int size = snprintf(double_buff, 1024, "%.4lf", test_double);
wxString result(double_buff, size);
}
int size = snprintf(double_buff, 1024, "%.4lf", test_double);
assert(string(double_buff, size) == expected_str);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment