【发布时间】:2012-08-16 04:17:09
【问题描述】:
#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 测试:1.125 s ; printf 测试:0.195 秒
- std::cout 测试:1.154 s ; printf 测试:0.230 秒
- std::cout 测试:1.142 s ; printf 测试:0.216 秒
- std::cout 测试:1.322 s ; printf 测试:0.221 秒
- std::cout 测试:1.108 s ; printf 测试:0.232 秒
如您所见,使用printf,然后使用fflushing 所用时间比使用std::cout 少约5 倍。
虽然我确实预计使用std::cout 的<< 运算符可能会慢一些(几乎是最小的),但我并没有为这种巨大的差异做好准备。我在做一个公平的测试吗?如果是这样,那么是什么让第一个测试比第二个测试慢得多,如果它们本质上做的是完全相同的事情?
【问题讨论】:
-
他也确实在 printf 版本中刷新过,所以不可能吗?
-
possible duplicate 问题没有回答我的主要问题,
**what makes** the first test so much slower than the second one...即 为什么 printf 究竟更快? -
除了您使用的库实现的质量之外,可能没有一个正确的答案。 this linked one等类似的问题已经出现过。阅读它以及它链接到的相关问题。
-
注意
std::cout << "Hello, World! (" << i << ")" << std::endl;是4个函数调用,而printf只有一个。尝试做printf5 次,就像cout一样,看看会发生什么。然后你会意识到有多少性能失败是由于函数调用,还有多少是由于库本身。 -
您当前的时间是没有意义的,因为 std::cout 与 stdout 同步,因此需要做很多“额外”的工作来保持同步。如果你解耦它们,你会看到加速(它仍然更慢)
std::cout.sync_with_stdio(false);
标签: c++ performance printf cout