基于算法竞赛的c++编程(21)cin,scanf性能差距和优化
cin 与 scanf 的性能差距
cin
是 C++ 标准库中的输入流对象,属于高级抽象,提供了类型安全和易用性,但性能通常低于 scanf
。scanf
是 C 标准库函数,直接处理原始字符输入,避免了 C++ 的额外开销(如 locale 处理、类型检查等)。性能差距主要体现在以下方面:
- 同步开销:默认情况下,
cin
与stdio
同步(ios_base::sync_with_stdio(false)
可关闭),这会引入额外锁机制。关闭同步后,cin
性能接近scanf
。 - 类型安全:
cin
通过运算符重载实现类型检查,而scanf
直接解析格式字符串,后者更轻量。 - 缓冲策略:
cin
可能使用更复杂的缓冲机制,而scanf
直接操作底层缓冲区。
优化 C++ 输入性能的方法
关闭同步
关闭 cin
与 stdio
的同步可以显著提升性能,但混合使用 cin
和 scanf
会导致未定义行为。
ios_base::sync_with_stdio(false);
cin.tie(nullptr); // 解除 cin 与 cout 的绑定
使用快速输入函数
对于大量数据读取,自定义快速输入函数(如逐字符读取)比 cin
或 scanf
更快。
int read_int() {int x = 0;char c = getchar_unlocked(); // 非标准但高效while (isdigit(c)) {x = x * 10 + (c - '0');c = getchar_unlocked();}return x;
}
预分配缓冲区
手动分配大缓冲区可以减少系统调用次数。
char buf[1 << 20];
setvbuf(stdin, buf, _IOFBF, sizeof(buf));
避免频繁格式化
scanf
的格式化解析较慢,直接读取原始数据后处理可能更快。
fread(buf, 1, sizeof(buf), stdin); // 批量读取
char* ptr = buf;
while (*ptr >= '0') {int x = 0;while (*ptr >= '0') x = x * 10 + (*ptr++ - '0');ptr++;
}
使用内存映射
对于文件输入,内存映射(mmap)可以绕过标准库直接访问数据。
int fd = open("input.txt", O_RDONLY);
char* data = (char*)mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
性能对比示例
以下代码对比了不同输入方法的性能:
#include <iostream>
#include <cstdio>
#include <chrono>void test_cin() {int x;while (std::cin >> x) {}
}void test_scanf() {int x;while (scanf("%d", &x) == 1) {}
}int main() {auto start = std::chrono::high_resolution_clock::now();test_scanf(); // 或 test_cin()auto end = std::chrono::high_resolution_clock::now();std::cout << "Time: " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms\n";
}
适用场景建议
- 开发效率优先:使用
cin
并关闭同步。 - 性能关键场景:使用
scanf
或自定义快速输入。 - 竞赛编程:通常关闭同步并绑定
cin
到nullptr
。