|
楼主 |
发表于 2009-12-20 00:20
|
显示全部楼层
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
原帖由 老伙计2008 于 2009-12-19 20:06 发表
学习了好久,有很多东西还是理解不透,不知道一下代码能否进行优化。先谢了!
说明:所有变量均为Byte型If X1 = Y1 Or X1 = Y2 Or X1 = Y3 Or X1 = Y4 Or X1 = Y5 Or X1 = Y6 _
Or X2 = Y1 Or X2 ...
可以这样写(test2):- Sub test1()
- Dim x1 As Byte, x2 As Byte, x3 As Byte, x4 As Byte, x5 As Byte, x6 As Byte
- Dim y1 As Byte, y2 As Byte, y3 As Byte, y4 As Byte, y5 As Byte, y6 As Byte
- x1 = 0: y1 = 0
- x2 = 0: y2 = 0
- x3 = 0: y3 = 0
- x4 = 0: y4 = 0
- x5 = 0: y5 = 0
- x6 = 0: y6 = 0
- Dim i As Long
- Dim j As Long
- Dim t As Single
- i = 0: j = 0
- t = Timer
- '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
- For j = 1 To 1000000
- If x1 = y1 Or x1 = y2 Or x1 = y3 Or x1 = y4 Or x1 = y5 Or x1 = y6 _
- Or x2 = y1 Or x2 = y2 Or x2 = y3 Or x2 = y4 Or x2 = y5 Or x2 = y6 _
- Or x3 = y1 Or x3 = y2 Or x3 = y3 Or x3 = y4 Or x3 = y5 Or x3 = y6 _
- Or x4 = y1 Or x4 = y2 Or x4 = y3 Or x4 = y4 Or x4 = y5 Or x4 = y6 _
- Or x5 = y1 Or x5 = y2 Or x5 = y3 Or x5 = y4 Or x5 = y5 Or x5 = y6 _
- Or x6 = y1 Or x6 = y2 Or x6 = y3 Or x6 = y4 Or x6 = y5 Or x6 = y6 Then i = i + 1
- Next
- '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
- t = Timer - t
- MsgBox CStr(t) & " i=" & CStr(i)
- End Sub
- '-----------------------------------------------------------------------------------------------------------
- Sub test2()
- Dim x1 As Byte, x2 As Byte, x3 As Byte, x4 As Byte, x5 As Byte, x6 As Byte
- Dim y1 As Byte, y2 As Byte, y3 As Byte, y4 As Byte, y5 As Byte, y6 As Byte
- x1 = 0: y1 = 0
- x2 = 0: y2 = 0
- x3 = 0: y3 = 0
- x4 = 0: y4 = 0
- x5 = 0: y5 = 0
- x6 = 0: y6 = 0
- Dim i As Long
- Dim j As Long
- Dim t As Single, ck As Boolean
- i = 0: j = 0
- t = Timer
- '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
- For j = 1 To 1000000
- ck = False
- '下面的代码和test1不等价,是错误程序
- If x1 = y1 Then
- ck = True
- ElseIf x2 = y2 Then
- ck = True
- ElseIf x3 = y3 Then
- ck = True
- ElseIf x4 = y4 Then
- ck = True
- ElseIf x5 = y5 Then
- ck = True
- ElseIf x6 = y6 Then
- ck = True
- End If
- If ck Then i = i + 1
- Next
- '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
- t = Timer - t
- MsgBox CStr(t) & " i=" & CStr(i)
- End Sub
复制代码 在我的电脑上 test1在任何情况下耗时稳定在 2.2s左右
test2在x1-x6 与y1-y6两两相等的时候耗时约0.26s,在极端的情况下(两两不相等)耗时0.5s左右
总体来说test2比test1快4倍左右。
刚刚楼上的回帖我采用的是用数组储存那12个变量,然后用双循环判断是否相等,如果遇到相等则退出循环,确认条件成立,结果一开始我测试的数据是12个变量两两相等的情况,耗时大约0.53s左右,当时急急忙忙回帖,回完了之后才发现测试的有问题,于是马上弄了个两两不相等的情况测试,发现在极端情况下,效率极低,耗时居然达到了7.2s左右
所以接着有帮上楼给删了,重新像本楼这样写。
此楼结果仍然错误!
[ 本帖最后由 Moneky 于 2009-12-20 01:37 编辑 ] |
|