組合語言有效能優勢,C#有靈活性,組織圖優勢。兩者結合使用是我的理想。
想法是大的組件和類層次使用C#;關鍵子程式使用彙編DLL。
可以從網上下載MASM32工具包。版本可以是8.2或者9.0。
我用彙編寫了一個DLL。功能是求和整數數組。
.386
.model flat, stdcall
option casemap:none
include \masm32\include\windows.inc
include \masm32\include\kernel32.inc
include \masm32\include\user32.inc
includelib \masm32\lib\user32.lib
includelib \masm32\lib\kernel32.lib
.code
LibMain proc hInstDLL:DWORD, reason:DWORD, unused:DWORD
.if reason == DLL_PROCESS_ATTACH
MOV EAX,TRUE
ret
.endif
ret
LibMain Endp
SumArray proc StdCall point:DWORD,len:DWORD
push esi
push ebx
mov esi,point
mov ebx,len
mov eax,[esi]
dec ebx
.if ! zero?
.repeat
add esi,4
add eax,[esi]
dec ebx
.until zero?
.endif
pop ebx
pop esi
ret
SumArray endp
End LibMain
我也是剛學的彙編,如果有什麼失誤的話,就請多指教了。
儲存為dll.asm之後,點project->build all菜單。已經產生了dll.obj。
之後寫dll.def檔案:
LIBRARY dll
EXPORTS SumArray
運行masm32/bin目錄下的命令link /subsystem:windows /dll /def:d:/project/asm/dll.def d:/project/asm/dll.obj
這樣在bin目錄下就有了dll.dll檔案。(不是很熟,勿笑)
在C#裡調用這個dll並不複雜。
1.將那個dll.dll拷貝到bin/debug目錄下。
2.加上using System.Runtime.InteropServices;
3.聲明外部方法
[DllImport("dll.dll")]
public static extern Int32 SumArray(Int32* point, Int32 length);
4.調用
sum = SumArray(point, source.Length);
5.因為使用了指標,所以需要把類設為unsafe;
public unsafe partial class Form1
6.設定項目的unsafe屬性。
我編了段程式測試它的效能:
int[] source = new int[100000];
Random random = new Random();
for (int i = 0; i < source.Length; i++)
{
source[i] = random.Next(100);
}
int sum=0;
long start = Environment.TickCount;
for (int time = 0; time < 1000; time++)
{
sum = 0;
foreach (int v in source)
{
sum += v;
}
}
long cost = Environment.TickCount - start;
Console.WriteLine("MSIL result={0};cost={1}", sum, cost);
start = Environment.TickCount;
for (int time = 0; time < 1000; time++)
{
sum = 0;
fixed(int* pstart = source, pend = &source[source.Length-1])
{
for (int* pnow=pstart; pnow < pend; pnow++)
{
sum += *pnow;
}
}
}
cost = Environment.TickCount - start;
Console.WriteLine("CSP result={0};cost={1}", sum, cost);
fixed (int* point = source)
{
start = Environment.TickCount;
for (int time = 0; time < 1000; time++)
{
sum = CalArray(point, source.Length);
}
cost = Environment.TickCount - start;
Console.WriteLine("MASM result={0};cost={1}",sum,cost);
}
跑下來的結果,C#遍曆求和平均630毫秒,C#指標求和420毫秒,彙編求和180毫秒。這還沒用MMX。
原文地址:http://www.cnblogs.com/fujingqiu/ 作者應該是:fujingqiu 吧