编写自定义 FPrintF

Writing Custom FPrintF

我必须制作自己的 fprintf 方法,但是通过比较我的方法与标准方法的执行时间,我的方法慢了将近 3 倍。我做错了什么?

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] = '[=10=]';
      tbuf += buf;
   }
   va_end(ap);
   Write((char*)tbuf.c_str(), tbuf.size());
}

你做错了什么。

好吧,对于您正在使用 sprintf 构建输出的人来说,这几乎可以完成您想要做的事情,而这不是 *printf 系列函数所做的。查看任何 printf 代码实现。

更好,你为什么不使用它呢?

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