我正在努力优化我的软件,并且我需要改变我存储和绘制东西的方式。
很多人说fmt在做这些事情上比iostream快得多,但我却坐在这里试图理解我做错了什么。
旧代码起作用了:
auto type = actor->GetName();
char name[0x64];
if (type.find("AI") != std::string::npos)
sprintf(name, "AI [%dm]", dist);
新的不是:
auto type = actor->GetName();
char name[0x64];
if (type.find("AI") != std::string::npos)
fmt::sprintf("AI [%dm]", dist);
我做错了什么?
发布于 2021-11-19 20:05:13
正如@NathanPierson在注释中提到的,fmt::sprintf()
返回一个std::string
,这是您忽略的。fmt::sprintf()
不填充char[]
缓冲区(并不是说您要将一个缓冲区传递给它,就像使用::sprintf()
那样)。
改变这一点:
char name[0x64];
fmt::sprintf("AI [%dm]", dist);
对此:
std::string name = fmt::sprintf("AI [%dm]", dist);
然后您可以根据需要使用name
。如果您需要将它传递给期望使用(const) char*
的函数,则可以为此使用name.c_str()
或name.data()
。
发布于 2021-11-19 20:14:18
很多人都说fmt在做这些事情上比iostream快得多,然而我却坐在这里试图理解我做错了什么。
除了雷米·莱博的正确答案,还有另外一点。你提到速度是个考虑因素。在这种情况下,您可能希望避免构造std::string
,并使用fmt::format_to_n()
(或std::format_to_n
)直接格式化为char缓冲区:
auto type = actor->GetName();
char name[0x64];
if (type.find("AI") != std::string::npos) {
fmt::format_to_n(name, 0x64, "AI [{}m]", dist);
}
不幸的是,我认为fmt
没有针对现有缓冲区并使用printf格式说明符的函数。
https://stackoverflow.com/questions/70039836
复制相似问题