[英]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] = '\0';
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.