Search code examples
vb.netoptimizationmathematical-optimization

Code optimization on minutes pr hour calculation


The following code takes a timeframe in minutes since midnight and creates an array with 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


Solution

  • 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.