Skip to content

Instantly share code, notes, and snippets.

@paroj
Created March 7, 2017 12:59
Show Gist options
  • Save paroj/f88655613ea6e28c6a119364b6dc13a4 to your computer and use it in GitHub Desktop.
Save paroj/f88655613ea6e28c6a119364b6dc13a4 to your computer and use it in GitHub Desktop.
performance of string conversions
#include <cstring>
#include <cmath>
#include <cstdio>
#include <ctime>
#include <cstdlib>
#include <sstream>
#define NITER 5000000
int main() {
const char* pi_s = " 3.14159265358979323846 "; // M_PI
float f;
clock_t t;
f = atoi(pi_s);
printf("test %f\n", f);
t = clock();
for(size_t i = 0; i < NITER; i++)
f = atof(pi_s);
printf("strtof %fs\n", float(clock() - t)/CLOCKS_PER_SEC);
t = clock();
for(size_t i = 0; i < NITER; i++)
f = strtof(pi_s, NULL);
printf("atof %fs \n", float(clock() - t)/CLOCKS_PER_SEC);
t = clock();
for(size_t i = 0; i < NITER; i++)
sscanf(pi_s, "%f", &f);
printf("sscanf %fs\n", float(clock() - t)/CLOCKS_PER_SEC);
t = clock();
std::stringstream ss;
for(size_t i = 0; i < NITER; i++) {
ss.str(pi_s);
ss.clear();
ss >> f;
}
printf("std::stringstream reuse %fs\n", float(clock() - t)/CLOCKS_PER_SEC);
t = clock();
for(size_t i = 0; i < NITER; i++)
std::stringstream(pi_s) >> f;
printf("std::stringstream %fs\n", float(clock() - t)/CLOCKS_PER_SEC);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment