为什么我的程序在重定向stdout时运行得更快?

时间:2013-11-20 23:43:22

标签: c++ linux optimization stdout benchmarking

我看到一些非常奇怪的东西。我编写了一个很小的代码计时器来捕获运行代码块的时间。我不能发布所有代码,它非常大,但我已经遇到了问题,并且没有任何东西靠近std :: cout

$ bin/profiler 50 
50 repetitions of Generate Config MLP took: 254 microseconds
50 repetitions of Create Population took: 5318 microseconds
50 repetitions of Create and Score Population took: 218047 microseconds

$ bin/profiler 50 > time_times
$ cat time_times 
50 repetitions of Generate Config MLP took: 258 microseconds
50 repetitions of Create Population took: 5438 microseconds
50 repetitions of Create and Score Population took: 168379 microseconds

$ bin/profiler 50 
50 repetitions of Generate Config MLP took: 269 microseconds
50 repetitions of Create Population took: 5447 microseconds
50 repetitions of Create and Score Population took: 216262 microseconds

$ bin/profiler 50 > time_times
$ cat time_times 
50 repetitions of Generate Config MLP took: 260 microseconds
50 repetitions of Create Population took: 5321 microseconds
50 repetitions of Create and Score Population took: 169431 microseconds

这是我用来计时的块,函数ptr只是一个void函数的链接,它只进行一次函数调用。我知道可能有更好的方法来计时,我想要快速和肮脏,所以我开始改进代码。

void timeAndDisplay(string name,function_ptr f_ptr) {

    struct timeval start, end;
    long mtime, seconds, useconds;

    gettimeofday(&start, NULL);
    // Run the code 
    for (unsigned x = 0; x < reps; x++) {
        f_ptr();
    }

    gettimeofday(&end, NULL);
    seconds  = end.tv_sec  - start.tv_sec;
    useconds = end.tv_usec - start.tv_usec;
    mtime = ((seconds) * 1000000 + useconds/1.0) + 0.0005;

    std::cout << reps << " repetitions of " << name << " took: " << mtime << " microseconds" << std::endl;
}

我正在编译和链接:

g++ -c -Wall  -O3 -fopenmp -mfpmath=sse -march=native src/profiler.cpp -o build/profiler.o
g++ build/*.o -lprotobuf -lgomp -lboost_system -lboost_filesystem  -o bin/profiler

我即将开始进行更改,所以我认为我会保存基线,但是当我重定向时,创建和分数的表现会有所不同!

有人知道发生了什么吗?

更新1: 第一次通过剖析没有显示任何重要的。几乎所有顶级调用都与程序运行的向量数学有关(特征库)。流行的理论是控制台有一些阻塞,但是对std :: cout的调用是在函数循环之外,总共只有3个,所以我觉得很难接受它有这样的影响。

更新2: 在让我疯狂一段时间之后,我放弃了一点,并开始用我可用的数据改进我的程序。它更奇怪,但我认为我找到了一个主要的影响因素 - 可用的系统熵。我的程序使用了大量的随机数,并且在使用任何一种方法运行了很多次后,它似乎以较慢的速度运行。我使用for循环来模拟这两种方法,虽然stdout重定向的速度更快,但我怀疑这个微小的IO块会随意移动一点点,这就是它更快的原因。我还在调查,但如果有人能指出我正确的方向来证明这一点我会非常感激。

3 个答案:

答案 0 :(得分:3)

在标准控制台输入/输出系统上写入或从中写入涉及缓冲区和锁定。所以我会说你通常会因锁定缓冲而受到性能影响。

我会建议以下Profiler找出花费最长时间的事情。

答案 1 :(得分:1)

写入控制台涉及图形处理,也可能处理回车(移动到行的开头)和换行(将所有前一个文本向上移动一行并删除顶行)。

重定向到文件通常更快,因为附加了输出并且没有进行图形处理。

至少那是我的经历。

答案 2 :(得分:0)

您是否尝试在屏幕外或其他窗口后面运行窗口,以便不必绘制它?我曾经在某些系统中绕过重绘窗口。

相关问题