using namespace System;
#define ARRAY_SIZE 1000
struct bubbleBase
{
int value;
};
class bubble1:public bubbleBase
{
public:
virtual int getvalue(){return value;}
virtual void setvalue(int newvalue){value=newvalue;}
};
class bubble2:public bubbleBase
{
public:
virtual int __clrcall getvalue(){return value;}
virtual void __clrcall setvalue(int newvalue){value=newvalue;}
};
template<class T>
void bubbleSort(int length)
{
TimeSpan ts;
T* array1=new T[ARRAY_SIZE];
for (int i=0;i<ARRAY_SIZE ;i++)
{
array1[i].setvalue(ARRAY_SIZE-i-1);
}
Int64 ticks=DateTime::Now.Ticks;
int i, j,temp, test;
for(i = length - 1; i > 0; i--)
{
test=0;
for(j = 0; j < i; j++)
{
if(array1[j].getvalue() > array1[j+1].getvalue())
{
temp = array1[j].getvalue();
array1[j].setvalue(array1[j+1].getvalue());
array1[j+1] .setvalue(temp);
test=1;
}
}
if(test==0) break;
}
ts=TimeSpan::FromTicks(DateTime::Now.Ticks-ticks);
Console::WriteLine("BubbleSort {0} Items: {1} Ticks",
ARRAY_SIZE,
ts.Ticks );
delete array1;
}
int main(array<System::String ^> ^args)
{
bubbleSort<bubble1>(ARRAY_SIZE);
bubbleSort<bubble2>(ARRAY_SIZE);
return 0;
}
運行結果是
BubbleSort 1000 Items: 3281250 Ticks
BubbleSort 1000 Items: 312500 Ticks
可以看到,__clrcall會大大加快在托管代碼中調用托管函數的速度。
順便說一下,在隨VC8.0發布的STL中增加了很多安全特性,但是這也會造成程序的運行速度減慢。如果你確認程序不會有緩沖區溢出或者內存越界訪問的問題,那麼可以把_SECURE_SCL定義成0來關掉這個特性。