2017-10-19 62 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'將其直接轉儲到您的文件中。 –