cout 为啥慢

有时候为了分析数据,需要打印大量的数据,几百万行。如果用std::cout << xxx << std::endl;会发现巨慢无比。原因是每行数据被发送到终端程序,当用了std::endl时,会刷新缓存,从而造成频繁的系统调用。如下面的测试程序:


#include 
#include 
#include 

int main ()
{
    const int tests = 10000000;
    
    time_t start = time (0);
    for (int i = 0; i < tests; ++i)
        std::cout << i << std::endl;
    time_t end = time (0);
    std::cerr << "use endl cost:" << (float)difftime (end, start) << std::endl;
    
    start = time (0);
    for (int i = 0; i < tests; ++i)
        std::cout << i << '\n';
    end = time (0);
    std::cerr << "use \\n cost:" << (float)difftime (end, start) << std::endl;
   
    return 0;
}


输出:
use endl cost:7
use \n cost:0

运行的时候用strace下, 获得使用std::endl的系统调用:


write(1, "9799200\n", 8)                = 8
write(1, "9799201\n", 8)                = 8
write(1, "9799202\n", 8)                = 8
write(1, "9799203\n", 8)                = 8
write(1, "9799204\n", 8)                = 8
write(1, "9799205\n", 8)                = 8
write(1, "9799206\n", 8)                = 8
write(1, "9799207\n", 8)                = 8
write(1, "9799208\n", 8)                = 8
write(1, "9799209\n", 8)                = 8
write(1, "9799210\n", 8)                = 8
write(1, "9799211\n", 8)                = 8


使用'\n'的系统调用:

write(1, "0\n9995401\n9995402\n9995403\n999540"..., 4096) = 4096
write(1, "2\n9995913\n9995914\n9995915\n999591"..., 4096) = 4096
write(1, "4\n9996425\n9996426\n9996427\n999642"..., 4096) = 4096
write(1, "6\n9996937\n9996938\n9996939\n999694"..., 4096) = 4096
write(1, "8\n9997449\n9997450\n9997451\n999745"..., 4096) = 4096
write(1, "0\n9997961\n9997962\n9997963\n999796"..., 4096) = 4096
write(1, "2\n9998473\n9998474\n9998475\n999847"..., 4096) = 4096
write(1, "4\n9998985\n9998986\n9998987\n999898"..., 4096) = 4096
write(1, "6\n9999497\n9999498\n9999499\n999950"..., 4026) = 4026

 可以看出,'\n'系统调用的次数会大大减少。

 这仅仅是个小坑,但有时不要被编码的不良习惯和粘贴复制拖累了开发进度。没有经验的情况下用下pgrof和strace啥的哈。


 另外,设置 sync_with_stdio(false) , 用 '\n' 不用 endl 就好了. 关掉这个的 cout 应该比 printf 快. 另看到 benchmark 称 sstream 比 snprintf 慢。

你可能感兴趣的:(视频)