cin和scanf的效率差异

来源:互联网 发布:服务器怎么开放端口 编辑:程序博客网 时间:2024/05/16 09:49
cin和scanf的效率差异
最近在在OJ上水了一道算法题,提交总是TLE(time limit:1000MS)总以为是自己的算法不够优化,无论怎么努力始终过不了,有种崩溃的感觉。无意间把cin换成了scanf竟然AC了,时间114MS。难道cin和scanf差距效率差异真的这么大吗?cin读入效率比scanf慢这个大家应该都是知道的,但为什么慢。博主结合请教大神和去Google,百度总结出一点原因:
关于cin官方文档是这样说的:

The global objects std::cin and std::wcin control input from a stream buffer of implementation-defined type (derived from std::streambuf), associated with the standard C input stream stdin.

These objects are guaranteed to be constructed before the first constructor of a static object is called and they are guaranteed to outlive the last destructor of a static object, so that it is always possible to read from std::cin in user code.

Unless sync_with_stdio(false) has been issued, it is safe to concurrently access these objects from multiple threads for both formatted and unformatted input.

Once std::cin is constructed, std::cin.tie() returns &std::cout, and likewise, std::wcin.tie() returns &std::wcout. This means that any formatted input operation on std::cin forces a call to std::cout.flush() if any characters are pending for output.

一个比较合理的原因是:C++中cin为了和scanf保持同步, 这样大家可以混用两种方法,不至于文件指针乱码导致发生错误,因此cin会牺牲掉一点效率。如果想解除这种同步,可以使用语句cin.sync_with_stdio(false)。这样cin和scanf的效率基本相差不大。有人做了cin和scanf具体的读入时间测试,可以参见https://www.byvoid.com/blog/fast-readfile
1 0