我有以下代码行:
printf("nnTime taken for simulation: %ld millisecondsn", duration.count() );
在我的家用机器上,我收到错误
main.cpp:292:65: error: format specifies type 'long' but the argument has type 'std::__1::chrono::duration<long long, std::__1::ratio<1, 1000>>::rep' (aka 'long long') [-Werror,-Wformat]
如果我将%ld更改为%lld,则会解决此错误我使用g++ -std=c++14
。主编译器版本为:
Apple clang version 12.0.5 (clang-1205.0.22.11)
Target: arm64-apple-darwin20.6.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
在我操作的linux集群上,如果用%lld运行它,我会得到以下错误,
main.cpp:229:83: error: format ‘%lld’ expects argument of type ‘long long int’, but argument 2 has type ‘std::chrono::duration<long int, std::ratio<1, 1000> >::rep {aka long int}’ [-Werror=format=]
我使用g++ -std=c++14
。群集编译器版本为:
g++ (GCC) 7.3.1 20180303 (Red Hat 7.3.1-5)
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
如果我将%lld更改为%ld,则一切都很好。
有没有一种方法可以打印出duration.count((,其中duration定义为auto duration = std::chrono::duration_cast<std::chrono::milliseconds> (stop-start);
其中stop、start是由std::chrono::high_resolution_clock::now();
指定的类型的变量。
如有任何建议,我们将不胜感激。
一个简单的解决方案是无条件地转换为long long
:
long long count = duration.count();
printf("%lld", count);
另一方面,我建议避免使用printf
及其脚踏板。
(假设需要使用printf()
(
将类型定义与说明符定义结合起来:
typedef my_duration_t std::chrono::duration<long long, std::milli>;
#define MY_DURATION_SPECIFIER "%lld"
然后你写:
auto duration = std::chrono::duration_cast<my_duration_t> (stop-start);
printf(
"nnTime taken for simulation: " MY_DURATION_SPECIFIER " millisecondsn",
duration.count()
);
这种(丑陋的(方法是stdint.h
中用于大小特定整数说明符的方法:
printf("Easy as " PRId64 "!n", ((int64_t) 123));
另请参阅此处。
如果使用#include <cinttypes>
,许多类型都有格式宏,但std::chrono::duration
似乎没有宏。
您可以考虑使用字符串流:
std::stringstream ss;
ss << duration.count();
printf("%s", ss.str().c_str());
(假设您需要使用printf()
(
使用中间std::stringstream
:
std::stringstream ss;
ss << "nnTime taken for simulation: " << duration.count() << "n";
printf("%s",ss.str().c_str());
// or instead of the last line: puts(ss.str().c_str());
考虑在所有情况下使用std::cout。
关于两者之间的速度差异,考虑使用:
std::ios::sync_with_stdio(false);
在代码的开头。只有当您用C++替代品替换所有printf/scanf(以及类似的(使用时,这才有效。
使用这个应该可以消除速度差。