[英]Writing Custom FPrintF
I have to make my own fprintf
method, but by comparing the execution time of my method with the standard one, mine is almost 3 times slower.我必须制作自己的fprintf
方法,但是通过将我的方法与标准方法的执行时间进行比较,我的方法几乎慢了 3 倍。 What have I done wrong?我做错了什么?
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());
}
What have you done wrong.你做错了什么。
Well for one you are using sprintf to construct your output, which pretty much does what you're trying to do, which is NOT what *printf series of functions do.好吧,对于您使用 sprintf 构建输出的人来说,它几乎可以完成您想要做的事情,而这不是 *printf 系列函数所做的。 have a look at any printf code implementation.看看任何 printf 代码实现。
Better yet why don't you use it?更好的是你为什么不使用它?
#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.