Skip to content

Instantly share code, notes, and snippets.

@kaityo256
Created November 6, 2015 08:58
Show Gist options
  • Save kaityo256/d2e876cf25dea0f83d04 to your computer and use it in GitHub Desktop.
Save kaityo256/d2e876cf25dea0f83d04 to your computer and use it in GitHub Desktop.
benchmark for std::stringstream
//----------------------------------------------------------------------
#include <iostream>
#include <string>
#include <stdlib.h>
#include <sstream>
#include <vector>
#include <sys/time.h>
//----------------------------------------------------------------------
const int TRIAL = 500000;
const int LEN = 100;
//----------------------------------------------------------------------
double
myrand(void){
return static_cast<double>(rand())/(static_cast<double>(RAND_MAX));
}
//----------------------------------------------------------------------
int
myrand2(void){
return static_cast<int>(myrand()*10.0);
}
//----------------------------------------------------------------------
void
show(std::vector<std::string> &sv) {
for (int i = 0; i < sv.size(); i++) {
std::cout << sv[i] << std::endl;;
}
}
//----------------------------------------------------------------------
double
myclock(void) {
struct timeval t;
gettimeofday(&t, NULL);
return t.tv_sec + t.tv_usec * 1e-6;
}
//----------------------------------------------------------------------
void
test_ss(void) {
std::vector<std::string> sv;
for (int j = 0; j < TRIAL; j++) {
std::stringstream ss;
for (int i = 0; i < LEN; i++) {
ss << myrand2();
}
sv.push_back(ss.str());
}
//show(sv);
}
//----------------------------------------------------------------------
void
test_str(void) {
std::vector<std::string> sv;
for (int j = 0; j < TRIAL; j++) {
std::string str;
for (int i = 0; i < LEN; i++) {
str.append(1, myrand2() + '0');
}
sv.push_back(str);
}
//show(sv);
}
//----------------------------------------------------------------------
void
test_char(void) {
char str[LEN + 1];
str[LEN] = 0;
std::vector<std::string> sv;
for (int j = 0; j < TRIAL; j++) {
for (int i = 0; i < LEN; i++) {
str[i] = myrand2() + '0';
}
sv.push_back(str);
}
//show(sv);
}
//----------------------------------------------------------------------
void
measure(void(*pfunc)(), const char *name) {
double st = myclock();
pfunc();
double t = myclock() - st;
printf("%s %f [sec]\n", name, t);
}
//----------------------------------------------------------------------
int
main(void) {
measure(&test_ss, "stringstream");
measure(&test_str, "string");
measure(&test_char, "char");
}
//----------------------------------------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment