首页 > 解决方案 > 在 Windows 中加速 printf 和 cout

问题描述

Windows cout 和 printf 真的很慢,所以当发送大量数据时,它会降低应用程序的速度(它会在几天内运行代码以检查是否一切正常)。一种使其更快的方法是通过在 main() 函数的开头编写以下代码来使用缓冲区:

#ifndef __linux__   //Introduce this code at the beginning of main() to increase a lot the speed of cout in windows: 
char buffer_setvbuf[1024];setvbuf(stdout, buffer_setvbuf, _IOFBF, sizeof buffer_setvbuf); //¿¡¡Sometimes it does not print cout inside a function until cout is used in main() or end of buffer is reached.
#endif

但不幸的是,有时它不会打印数据,因为缓冲区未满。

然后问题: 1.如何强制打印:通过制作\n?2.如何禁用缓冲区?

标签: c++

解决方案


打印

我看到您正在尝试在内存上使用更大的缓冲区来减少stdout. 实际上,在缓冲区变满之前,您的代码不会打印任何内容,因为缓冲模式设置为_IOFBF(即完全缓冲)。由于您想控制何时刷新,有两种方法可以解决。

  1. 使用_IOLBF(即行缓冲),并在您想要刷新时放置换行符。
  2. 调用fflush(stdout)以手动刷新缓冲区。

标准::cout

我认为std::cout在编写 c++ 代码时应该首选它,因为它易于使用。可能会减慢 I/O 进程的一件事是 和 之间的iostream同步stdio。据我所知,许多系统的默认设置是使两者保持同步,这有一些开销。您可以通过调用禁用它std::ios_base::sync_with_stdio(false)参考

当您需要刷新输出时,您可以使用所谓的“操纵器”作为输出流 - 即std::flushstd::endl. 当这些操纵器被放入如下输出流中std::cout << "your string" << std::endl时:保证输出流被刷新。

std::endl 参考

std::flush 参考

底线

  1. 用于输出时用于fflush冲洗。stdoutprintf
  2. 我建议尝试std::cout关闭同步,并测试它是否符合您的性能需求。

推荐阅读