返回列表 上一主題 發帖

如何 測試 Excel VBA 計算時間間隔的 精確度?

如何 測試 Excel VBA 計算時間間隔的 精確度?

先丟出 一個問題,再慢慢 解答
希望大家有興趣
天下為公

  1. Sub main()
  2.    Dim no, i, t1, t2 As Long
  3.    Dim sum, dt As Double
  4.    
  5.    no = 100000000
  6.    ct = 0
  7.    
  8.    While (no > 1)
  9.       ct = ct + 1
  10.       
  11.       t1 = time1()
  12.       sum = 0#
  13.       For i = 1 To no
  14.          sum = sum + i
  15.       Next i
  16.       dt = time2(t1)
  17.       
  18.       Cells(ct, 1) = no
  19.       Cells(ct, 2) = dt
  20.       
  21.       no = no / 3
  22.    Wend
  23. End Sub

  24. Function time1() As Long
  25.    Dim a As Double

  26.    a = Timer * 1000
  27.    time1 = Int(a + 0.5)
  28. End Function

  29. Function time2(ByVal t1 As Long) As Double
  30.    Dim t2 As Long
  31.    Dim dt As Double
  32.    t2 = time1()
  33.    dt = (t2 - t1) / 1000#
  34.    
  35.    ' dt must >- 0.0
  36.    If (dt < 0#) Then
  37.       dt = dt + 86400#
  38.    End If
  39.    
  40.    time2 = dt
  41. End Function
複製代碼
回復 1# sjgau
天下為公

TOP

回復 2# sjgau
我覺得這樣有問題,Timer傳回的數為Single,
在我的電腦上,Timer傳回的數只會到小數點後第二位,
這個數是已經進位過的,而不該再用 timer1( ) 做四捨五入,

你可能會說,Timer傳回的數如果只到小數點後第二位,timer1( )裡的 a 小數點後就應該都是零,可是不是這樣。

這是因為你的 a 是 Double 資料型態,資料型態之間轉換造成的誤差,可 run 底下程式碼知道有此誤差:
  1. Sub Test()
  2.   Dim t1 As Single
  3.   Dim d1 As Double
  4.   
  5.   t1 = Timer
  6.   Debug.Print "t1=", t1
  7.   Debug.Print "Cdbl(t1)=", CDbl(t1)
  8.   d1 = t1
  9.   Debug.Print "d1=", d1
  10. End Sub
複製代碼

TOP

回復 3# stillfish00


    同意 您的看法,
SINGLE 的 精確度,只有 6 - 7位數,
所以,以上的測試 確實不太 科學
天下為公

TOP

回復 3# stillfish00

Timer 函數
請參閱     範例     特性

傳回一 Single,其內容為從前一個午夜算起到現在所經過的秒數。

語法

Timer

請注意

在 Microsoft Windows中, Timer函數傳回一秒的小數部分。
天下為公

TOP

        靜思自在 : 發脾氣是短暫的發瘋。
返回列表 上一主題