エラー処理のために戻り値を使用する場合、例外を使用する場合

13760 ワード

パフォーマンスの戻り値が例外より優れていることを考慮
プログラム中の高周波でエラー処理が発生した場合は、戻り値を使用します.
シナリオ:selectやepollなどを用いて複数の接続のデータをポーリングで読み出すことを考慮しなければ,このとき互いに干渉をブロックしないように非ブロックの読み出し関数を用いる.この場合readは、戻り値が一時的にデータ読み取りがないことを示すのではなく、異常を用いる戻り値-1が大量に発生する.では、パフォーマンスの消費は恐ろしいです.
単純なシミュレーションコードは次のとおりです.
#include
#include
#include
#include
#define ERROR_XXXX_XXXX  ((HRESULT)0xE1000008L)//       
using namespace std;

/*
           by https://blog.csdn.net/qq_26046771/article/details/106894723
*/

/*           _outbuff  
myread myread1       
*/

int randnum = 0;;//        
list<int> randnumlist;//  myread myread1        
int myread(char* _outbuff,int len) {
	/*......  ........*/
	
	/*         */
	if (randnum % 5 == 0)
	{
		return -1;
		SetLastError(ERROR_XXXX_XXXX);
	}
	else
	{
		memcpy_s(_outbuff, len, "hello kity", 11);
		return 11;
	}
}

int myread1(char* _outbuff, int len) {
	/*......  ........*/
		/*         */
	if (randnum % 5 == 0)
		throw "         ";
	memcpy_s(_outbuff, len, "hello kity", 11);
	return 11;
}

void test() {
	char buff[1000];
	srand(time(NULL));
	for (int i = 0; i < 1000000; ++i) {
		randnumlist.push_back(rand());
	}

	auto starttime = time(0);
	for (const auto&tmp:randnumlist) {
		randnum = tmp;
		if (myread(buff, 1000) != -1)
			cout << buff <<endl;
		else {
			if (GetLastError() == ERROR_XXXX_XXXX)
				;//    
		}
	}
	cout << "  :" << time(0) - starttime << endl;
	getchar();
	starttime = time(0);
	for (const auto &tmp : randnumlist) {
		randnum = tmp;
		try {
			myread1(buff,1000);
			cout << buff<<endl;
		}
		catch (const char* str) {
			;//    
		}
	}
	cout << "  :" << time(0) - starttime << endl;
}
int main() {
	test();
	return 0;
}

プログラム実行結果前者:消費時間:39後者消費時間:151
低周波エラー処理用異常----------戻り値のエラーは人為的にいい加減に処理を漏らす可能性がありますが、異常は処理しないとプログラムが停止し、処理プログラムにエラーを実行させ、予想とは異なる実行結果が発生しないようにします.同時に異常で戻る値よりずっと気持ちがいいです.
例えば、ユーザーがパラメータを入力したエラー、誰が無事にエラーパラメータを入力したかなどです.
ULONGLONG getfilelength(const string &filename);//                      
//.............
cout<<"         "<<endl;
cin>>filename;
cout<<"         :"<<getfilelength(filename)<<endl;

余談:特殊な戻り値がなくてエラー値を表したらどうしますか?
例えば次のように
bool Peer::getstate();

君はそうできる
bool Peer::getstate(int *_outres);// _outres