实验设计:
代码:
test.cpp
#include <iostream>
#include <ctime>
#include <cstdio>
using namespace std;
int main()
{
time_t start=time(NULL);
for(int i=0;i<99999999;i++)
printf("%d\n",i);
cout<<"spend time: "<<difftime(time(NULL),start)<<endl;
}
时间测试脚本:testTime1.sh
#!/bin/bash
starttime=$(date +%s)
./a.out
endtime=$(date +%s)
cost=$((endtime - starttime))
echo $cost
testTime2.sh
#!/bin/bash
starttime=$(date +%s)
./a.out > /dev/null
endtime=$(date +%s)
cost=$((endtime - starttime))
echo $cost
testTime2.sh
#!/bin/bash
starttime=$(date +%s)
./a.out > txt
endtime=$(date +%s)
cost=$((endtime - starttime))
echo $cost
运行三个脚本,第一个的结果是???s(天长地久),第二个的结果是14s,第三个的结果是14s。所以将输出重定向到/dev/null空设备或文件总中是有效的。
原因可能在于刷缓存,对于标准输出,由于及时性,所以需要频繁地刷缓存,将数据打到屏幕上,但如果是重定向空设备或文件中,可以先缓存大量数据再统一刷到磁盘(空设备中)。
但是上述三种情况调用的write系统调用的次数都是一样的,使用空设备和使用写文件的效率一样,所以对于调试信息打屏的处理一定是注释掉打屏,而非重定向到空设备。但是较之于输出到标准输出上,使用空设备、写文件还是有性能提升的。