-2

I have to make my own fprintf method, but by comparing the execution time of my method with the standard one, mine is almost 3 times slower. What have I done wrong?

void FPrintF(const char *aFormat, ...)
{
   va_list ap;
   const char *p;
   int count = 0;
   char buf[16];
   std::string tbuf;
   va_start(ap, aFormat);
   for (p = aFormat; *p; p++)
   {
      if (*p != '%')
      { 
         continue;
      }
      switch (*++p)
      { 
         case 'd':
            sprintf(buf, "%d", va_arg(ap, int32));
            break;
         case 'f':
            sprintf(buf, "%.5f", va_arg(ap, double));
            break;
         case 's':
            sprintf(buf, "%s", va_arg(ap, const char*));
            break;
      }
      *p++;
      const uint32 Length = (uint32)strlen(buf);
      buf[Length] = (char)*p;
      buf[Length + 1] = '\0';
      tbuf += buf;
   }
   va_end(ap);
   Write((char*)tbuf.c_str(), tbuf.size());
}
phuclv
  • 37,963
  • 15
  • 156
  • 475
Brian Batista
  • 67
  • 1
  • 6

1 Answers1

0

What have you done wrong.

Well for one you are using sprintf to construct your output, which pretty much does what you're trying to do, which is NOT what *printf series of functions do. have a look at any printf code implementation.

Better yet why don't you use it?

#include <cstdio>
#include <cstdarg>

namespace my {

void fprintf(const char *aFormat, ...)
{
        va_list ap;
        va_start(ap, aFormat);
        (void)vprintf(aFormat, ap);
        va_end(ap);
}

}

int main() {
    my::fprintf("answer is %d\n", 42);
    return 0;
}
Ahmed Masud
  • 21,655
  • 3
  • 33
  • 58
  • But I need to Write the buf to my file. I saw that the standard fprintf receives a FILE*, my custom fprintf is inside a FileHandle class and should write the buf to the final file. – Brian Batista Oct 19 '17 at 17:05
  • if you need to write it to a file you can use `vsnprintf` to create a string or `vfprintf` to dump it directly to your file. – Ahmed Masud Oct 19 '17 at 17:08