Office中国论坛/Access中国论坛

标题: 【原创 / 文章】最简单的方法 VS 最高的效率 [打印本页]

作者: LucasLynn    时间: 2005-8-28 05:47
标题: 【原创 / 文章】最简单的方法 VS 最高的效率
以下两个程序实现相同功能,将长度为4的字节数组转化成长整形变量。这也是一个常用的功能。

方法一:最常规的方法,按权累加,

Public Sub test1()

    Dim t1 As Single

    Dim t2 As Single

    Dim i As Long

    Dim a(3) As Byte

    Dim b As Long

   

    a(0) = 101

    a(1) = 123

    a(2) = 232

    a(3) = 78

   

    t1 = Timer

    For i = 1 To 10000000

        b = ((CLng(a(3)) * 256 + a(2)) * 256 + a(1)) * 256 + a(0)

    Next i

    t2 = Timer

   

    Debug.Print "单次耗时: " & (t2 - t1) / 10 & "微妙"

    Debug.Print "b = " & b

End Sub

计时结果:

b = 1323858789

单次耗时: .4289063微妙

方法二:采用API复制数据,直接合并四个字节变量为一个长整形变量。

Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (ByVal pDest As Any, ByVal pSrc As Any, ByVal ByteLen As Long)

Public Sub test2()

    Dim t1 As Single

    Dim t2 As Single

    Dim i As Long

    Dim a(3) As Byte

    Dim b As Long

   

    a(0) = 101

    a(1) = 123

    a(2) = 232

    a(3) = 78

   

    t1 = Timer

    For i = 1 To 10000000

        CopyMemory VarPtr(b), VarPtr(a(0)), 4

    Next i

    t2 = Timer

   

    Debug.Print "单次耗时: " & (t2 - t1) / 10 & "微妙"

    Debug.Print "b = " & b

End Sub

计时结果:

b = 1323858789

单次耗时: .2820312微妙

[此贴子已经被作者于2005-9-21 22:58:05编辑过]






欢迎光临 Office中国论坛/Access中国论坛 (http://www.office-cn.net/) Powered by Discuz! X3.3