// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>

#include <ctime>
#include <cstring>

using namespace std;

template <typename T>
inline string toString(const T& val, int wi, int pr = 0, char fi = ' ')
{
    stringstream tmp;
    if(wi > 0) tmp << setfill(fi) << setw(wi);
    if(pr >= 0) tmp << setprecision(pr);
    tmp << val;
    return tmp.str();
}

const int N = 10000000;

int main()
{
  time_t t1 = time(NULL);
  for(int i=0;i<N;i++)
  {
      char buf[5];
      sprintf(buf,"%04d",123);
      if(strcmp(buf,"0123")!=0)
      {
          cout << "error" << endl;
          return 1;
      }
  }
  time_t t2 = time(NULL);
  cout << "sprintf " << (t2 - t1) << " seconds" << endl;
  time_t t3 = time(NULL);
  for(int i=0;i<N;i++)
  {
      string buf = toString(123,4,0,'0');
      if(buf!=string("0123"))
      {
          cout << "error" << endl;
          return 1;
      }
  }
  
  time_t t4 = time(NULL);
  cout << "stringstream " << (t4 - t3) << " seconds" << endl;
}
