[英]Why does my program run faster when I redirect stdout?
我看到了一些很奇怪的东西。 我编写了一个微型代码计时器,以捕获运行了多长时间的代码块。 我不能发布所有代码,它很大,但是我已经遍历了有问题的代码块,并且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:进行概要分析的第一遍并没有显示任何重要意义。 几乎所有的调用都与程序正在运行的矢量数学有关(本征库)。 流行的理论是控制台有一些阻塞io,但是对std :: cout的调用不在函数循环之外,总共只有3个,因此我很难接受它会产生如此的影响。
更新2:在使我发疯了一段时间后,我放弃了一点,开始使用可用数据对程序进行改进。 这很奇怪,但我认为我发现了一个主要的影响因素-可用的系统熵。 我的程序使用了大量的随机数,并且在使用任何一种方法运行了多次之后,它的运行速度似乎都变慢了。 我使用了for循环来模拟这两种方法,尽管使用stdout重定向可以更快,但是我怀疑这块IO urandom很小,这就是为什么它更快的原因。 我仍在调查,但如果有人能指出正确的方向来证明这一点,我将不胜感激。
向标准控制台输入/输出系统写入数据或从标准控制台输入/输出系统写入数据涉及缓冲区和锁定。 因此,我要说的是,由于锁定缓冲区,通常会导致性能下降。
我建议使用以下Profiler来找出花费最长时间的内容。
写入控制台涉及图形操作,还可能处理回车符(移至行的开头)和换行符(将所有先前的文本上移一行并擦除第一行)。
重定向到文件通常更快,因为附加了输出并且不进行任何图形操作。
至少那是我的经验。
您是否尝试在窗口不在屏幕上或在另一个窗口后面的情况下运行它,而不必绘制它? 我曾在一些系统上可以绕过重绘窗口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.