c++ - 在 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.如何禁用缓冲区?
解决方案
打印
我看到您正在尝试在内存上使用更大的缓冲区来减少stdout
. 实际上,在缓冲区变满之前,您的代码不会打印任何内容,因为缓冲模式设置为_IOFBF
(即完全缓冲)。由于您想控制何时刷新,有两种方法可以解决。
- 使用
_IOLBF
(即行缓冲),并在您想要刷新时放置换行符。 - 调用
fflush(stdout)
以手动刷新缓冲区。
标准::cout
我认为std::cout
在编写 c++ 代码时应该首选它,因为它易于使用。可能会减慢 I/O 进程的一件事是 和 之间的iostream
同步stdio
。据我所知,许多系统的默认设置是使两者保持同步,这有一些开销。您可以通过调用禁用它std::ios_base::sync_with_stdio(false)
。参考
当您需要刷新输出时,您可以使用所谓的“操纵器”作为输出流 - 即std::flush
和std::endl
. 当这些操纵器被放入如下输出流中std::cout << "your string" << std::endl
时:保证输出流被刷新。
std::endl
参考
std::flush
参考
底线
- 用于输出时用于
fflush
冲洗。stdout
printf
- 我建议尝试
std::cout
关闭同步,并测试它是否符合您的性能需求。
推荐阅读
- python - Scrapy KeyError: 0 解析下一页
- python - Django datetime.date.min 和 Mysql DATE 最小值不同
- java - Thymeleaf - 一次加载元数据并在所有页面中使用
- android - Android 上内容过长时的 vCard 导入问题
- python - 如何使用 xlsxwriter 以英寸为单位设置行高?
- swift - 来自字符串的 Swift DateFormatter 日期在 NSDateFormatter 曾经工作的地方失败
- php - 将应用程序升级到 CodeIgniter 3 后出现问题
- c++ - 为什么我不能在循环中更改指针的内容?
- java - Apache Axis1 与 JDK11 的兼容性
- python - 绘制 Benford 定律的直方图