开发者

Code optimization on minutes pr hour calculation

The following code takes a timeframe in minutes since midnight and creates an array with开发者_Python百科 minutes pr hour. But, it's slow. Any better suggestions out there? (no, changing language is not an option :-) )

Const clDeparture   As Long = 123
Const clArrival     As Long = 233
Dim lHour           As Long
Dim lMinute         As Long
Dim alHour(25)      As Long

For lMinute = 0 To 1440
    If lMinute >= clDeparture And lMinute < clArrival Then
        alHour(Int(lMinute / 60)) = alHour(Int(lMinute / 60)) + 1
    End If
Next

The array should now contain:

(0,0) (1,0) (2,57) (3,53) (4,0) .....

Regards


You want to know how many minutes of each hour are in the time span?
I think this should do it, or something close to it:

lDepHour = Int(clDeparture / 60)
lDepMinute = clDeparture - lDepHour * 60
lArrHour = Int(clArrival / 60)
lArrMinute = clArrival - lArrHour * 60

If (lDepHour = lArrHour) Then
  alHour(lDepHour) = lArrMinute - lDepMinute
Else
  alHour(lDepHour) = 60 - lDepMinute
  alHour(lArrHour) = lArrMinute
  For lHour = lDepHour + 1 To lArrHour - 1
    alHour(lHour) = 60
  End For
End If

This should be about 60 times faster than what you've got.

P.S. If the time span can span midnight (arrival < departure) then add 24*60 to the arrival time, do the same logic, and if lHour >= 24, put the numbers in lHour - 24.


Well, how about:

For lMinute = clDeparture To clArrival - 1
    alHour(Int(lMinute / 60)) = alHour(Int(lMinute / 60)) + 1
Next

Given that you're only going to be taking any actions for minutes between clDeparture and clArrival, there's no point in looping through the rest of them.

That's a simple start. You could certainly improve it by looking through each hour instead of each minute and checking what proportion of that time was "covered" by the time period. That would be trickier, but certainly doable. I wouldn't want to venture to code that in VB, but I could probably whip up a C# version if you really wanted. I'd start off with the simple code and see if that's fast enough though.


Use integer arithmetic instead of floating point:

Int(lMinute / 60)

is the same as

lMinute \ 60

But the latter is faster because it uses integer division and saves the need to convert from Long to Double and back. Furthermore, VB6 doesn’t optimize well. If you need the value twice, consider storing the result in a variable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜