c++ - OS X 下使用 cin / cout 为什么会过慢?
高洛峰
高洛峰 2017-04-17 13:21:50
0
1
719
  1. 描述你的问题
    向下面这个程序输入 10000000 个随机数后再输出需要用掉约 18 秒时间,其中输入用掉约 15 秒,输出用掉约 3 秒。这个速度比一台配置较低的 Linux 系统(g++ 和 clang++ 都试过)和一台 Windows XP 虚拟机(g++)慢得多(不到 4 秒)。printf()scanf() 的速度是正常的。

  2. 贴上相关代码
    test.cpp:(random.txt 是随机数文件。编译选项为 clang++ test.cpp -o test。)

    #include <iostream>
    #include <ctime>
    #include <cstdio>
    using namespace std;
    
    const int length = 10000000;
    int array[length] = {};
    
    int main()
    {
        freopen("random.txt", "r", stdin);
        freopen("out.txt", "w", stdout);
        clock_t start1, end1, end2;
        start1 = clock();
        for (int i = 0; i < length; i++) cin >> array[i];
        end1 = clock();
    
        for (int i = 0; i < length; i++) cout << array[i];
        end2 = clock();
        freopen("result.txt", "w", stdout);
        cout << (double)(end1 - start1) / CLOCKS_PER_SEC << endl;
        cout << (double)(end2 - end1) / CLOCKS_PER_SEC << endl;
        return 0;
    }
  3. 贴上报错信息

  4. 贴上相关截图

  5. 已经尝试过哪些方法仍然没解决(附上相关链接)
    用 Instruments.app 的 Time Profiler 看过,但是看不懂……网上搜索过也没有结果。

更新:刚才又看了一遍 Instruments.app,发现 _pthread_mutex_unlock_slow_pthread_mutex_lock_slow 在输入中花掉了很多时间。但我不知道它们是做什么用的。

附:OS X 版本 10.11.3,Xcode 版本为 7.1.1。
clang 版本:

clang++ --version
Apple LLVM version 7.0.0 (clang-700.1.76)
Target: x86_64-apple-darwin15.3.0
Thread model: posix
高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(1)
伊谢尔伦

The reasons may be:

  1. For unknown reasons, the synchronization time with stdio is too long, please use std::ios::sync_with_stdio(false);

  2. The previous point is really a cliché. According to my own observation, libc++'s implementation of iostream is very slow. When both stdio synchronization is turned off at the same time, libstdc++ is 1100% faster. The default -stdlib specified by clang is libc++.

  3. (Explanation for the previous point) According to the results of Instruments.app, it is possible that libc++ implements thread safety for iostream. I have not looked at the code, but the provisions of thread safety in the standard are implementation-dependent.

Since the two versions tested above are shipped with OS X, and the libstdc++ that comes with OS X is very old, maybe the new version of libstdc++ also implements thread safety. Therefore, please re-run the test specifying -stdlib=libstdc++ and improve the test results of Instruments.app.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template