#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; }
现在,这里是前五场的时代:
> std :: cout test:1.125 s; printf测试:0.195秒
> std :: cout test:1.154 s; printf测试:0.230秒
> std :: cout test:1.142 s; printf测试:0.216 s
> std :: cout test:1.322 s; printf测试:0.221秒
> std :: cout test:1.108 s; printf测试:0.232秒
正如你所看到的,使用printf,然后刷新比使用std :: cout的时间少约5倍.
虽然我确实期望使用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; }
因此,您将只测试printf和cout函数调用之间的差异.您不会因多个<<电话等.如果你尝试这个,我怀疑你会得到不同的结果.