Skip to content

Instantly share code, notes, and snippets.

@paroj
Created Mar 7, 2017
Embed
What would you like to do?
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