1. 程式人生 > >打屏資訊的效率以及處理

打屏資訊的效率以及處理

實驗設計:

程式碼:

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系統呼叫的次數都是一樣的,使用空裝置和使用寫檔案的效率一樣,所以對於除錯資訊打屏的處理一定是註釋掉打屏,而非重定向到空裝置。但是較之於輸出到標準輸出上,使用空裝置、寫檔案還是有效能提升的。