编写自定义 FPrintF

Writing Custom FPrintF

本文关键字:FPrintF 自定义      更新时间:2023-10-16

我必须制作自己的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] = '';
      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("answerswer is %dn", 42);
    return 0;
}