#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
然后 fflush
使用 std::cout
所需的时间大约减少 5 倍.
虽然我确实希望使用 std::cout
的<<
运算符(operator)可能会慢一点(几乎是最小的),我没有为这种巨大的差异做好准备。我在做一个公平的测试吗?如果是这样,那么是什么让第一个测试比第二个测试慢得多,如果它们本质上做的是完全相同的事情?
最佳答案
试试这个:
#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;
}
然后我得到:
> 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
所以 P2 时间不会改变。
但是使用 std::cout.sync_with_stdio(false);
可以提高 P1 时间(即 std::cout)。因为代码不再尝试保持两个流 (std::cout stdout) 同步。如果您正在编写纯 C++ 并且仅使用 std::cout 则不是问题。
关于c++ - printf 比 std::cout 快 5 倍以上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12044357/