Search code examples
c++fileprintfgame-engineexecution-time

Writing Custom FPrintF


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());
}

Solution

  • 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;
    }