App*_*ker 14 c++ performance printf cout
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <ctime>
int main(int argc, char* argv[])
{
std::clock_t start;
double duration;
std::cout << "Starting std::cout test." << std::endl;
start = std::clock();
for (int i = 0; i < 1000; i++)
{
std::cout << "Hello, World! (" << i << ")" << std::endl;
}
duration = (std::clock() - start) / (double) CLOCKS_PER_SEC;
std::cout << "Ending std::cout test." << std::endl;
std::cout << "Time taken: " << duration << std::endl;
std::system("pause");
std::cout << "Starting std::printf test." << std::endl;
start = std::clock();
for (int i = 0; i < 1000; i++)
{
std::printf("Hello, World! (%i)\n", i);
std::fflush(stdout);
}
duration = (std::clock() - start) / (double) CLOCKS_PER_SEC;
std::cout << "Ending std::printf test." << std::endl;
std::cout << "Time taken: " << duration << std::endl;
system("pause");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
现在,这是前五次运行的时间:
如您所见,使用printf然后使用fflush比使用时间少5倍std::cout.
虽然我确实期望使用std::cout's <<运算符可能稍慢(几乎是最小),但我并没有为这个巨大的差异做好准备.我做了一个公平的测试吗?如果是这样,那么是什么让第一次测试比第二次测试慢得多,如果他们基本上做同样的事情呢?
Mar*_*ork 12
试试这个:
#include <cstdlib>
#include <cstdio>
#include <ctime>
#include <iostream>
int main(int argc, char* argv[])
{
#if defined(NOSYNC)
std::cout.sync_with_stdio(false);
#endif
std::cout << "Starting std::cout test." << std::endl;
std::clock_t start = std::clock();
for (int i = 0; i < 1000; i++)
{
std::cout << "Hello, World! (" << i << ")" << std::endl;
}
clock_t mid = std::clock();
for (int i = 0; i < 1000; i++)
{
std::printf("Hello, World! (%i)\n", i);
std::fflush(stdout);
}
std::clock_t end = std::clock();
std::cout << "Time taken: P1 " << ((mid-start)*1.0/CLOCKS_PER_SEC) << std::endl;
std::cout << "Time taken: P2 " << ((end-mid)*1.0/CLOCKS_PER_SEC) << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
然后我得到:
> g++ -O3 t13.cpp
> ./a.out
# lots of lines deleted
Time taken: P1 0.002517
Time taken: P2 0.001872
> g++ -O3 t13.cpp -DNOSYNC
> ./a.out
# lots of lines deleted
Time taken: P1 0.002398
Time taken: P2 0.001878
Run Code Online (Sandbox Code Playgroud)
所以P2时间不会改变.
但是你使用了P1时间(即std :: cout)的改进std::cout.sync_with_stdio(false);.因为代码不再试图保持两个流(std :: cout stdout)同步.如果您正在编写纯C++并且仅使用std :: cout而不是问题.
对于真正的苹果对苹果比较,重新编写测试,以便测试用例之间唯一的变化是使用的打印功能:
int main(int argc, char* argv[])
{
const char* teststring = "Test output string\n";
std::clock_t start;
double duration;
std::cout << "Starting std::cout test." << std::endl;
start = std::clock();
for (int i = 0; i < 1000; i++)
std::cout << teststring;
/* Display timing results, code trimmed for brevity */
for (int i = 0; i < 1000; i++) {
std::printf(teststring);
std::fflush(stdout);
}
/* Display timing results, code trimmed for brevity */
return 0;
}
Run Code Online (Sandbox Code Playgroud)
有了它,你将只测试printf和cout函数调用之间的差异.由于多次<<通话等原因,您不会产生任何差异.如果您尝试这样做,我怀疑您会得到一个非常不同的结果.