2017-10-19 81 views
-2

我必须在C++中创建自己的fprintf方法,但通过比较我的方法和标准方法的执行时间,我的速度几乎慢了3倍。我做错了什么?书写自定义FPrintF

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

errr你能解决你的问题的格式吗? –

+1

printf写得不错:)。并且通过许多编译来支持编译时间。 –

+1

你正在使用sprintf写出buf。然后,sprintf必须解析格式并执行输出。 – Blacksilver

回答

0

你做错了什么。

那么你正在使用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; 
} 
+0

但我需要将buf写入我的文件。我看到标准fprintf接收到FILE *,我的自定义fprintf在FileHandle类中,应该将buf写入最终文件。 –

+0

如果您需要将其写入文件,您可以使用'vsnprintf'创建一个字符串或'vfprintf'将其直接转储到您的文件中。 –