Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion of Date into hour/minute/second incredibly slow

I need a date cyclically convert into its components (hour, minute, second). The following code does this quite well.

Dim time_hour As Integer
Dim time_minute As Integer
Dim time_second As Integer
Dim time_ms As Integer
Dim storedNow As Date

storedNow = Now
time_hour = storedNow.Hour
time_minute = storedNow.Minute
time_second = storedNow.Second
time_ms = storedNow.Millisecond

However, I have found this a performance problem. I have examined the source code with a profiler, and the conversion of Now into its components seems to be incredibly slow. Is there a quick way to the current time to disassemble into its component parts?

like image 299
user730451 Avatar asked Apr 29 '11 04:04

user730451


1 Answers

Take a look at Extremoptimization.com. There are a few interesting mathematic thoughts about this. Here's a possible sketch of a solution:

Dim ticks As Long
Dim time_hour As Integer
Dim time_minute As Integer
Dim time_second As Integer
Dim time_ms As Integer
Dim storedNow As Date

storedNow = Now
ticks = storedNow.Ticks
time_ms = CInt((ticks \ 10000) Mod 86400000)
time_hour = CInt(Math.BigMul(time_ms >> 7, 9773437) >> 38)
time_ms -= 3600000 * time_hour
time_minute = CInt(((Math.BigMul(time_ms >> 5, 2290650)) >> 32))
time_ms -= 60000 * time_minute
time_second = ((time_ms >> 3) * 67109) >> 23
time_ms -= 1000 * time_second

But be careful. Your source code will not be maintainable. This does your conversion very reliable, but I'm not sure if anyone else would understand what you are doing on the first view. The reward is a conversion, that is about 25 times faster than the classic approach. However, you still should think about your approach and if it is not possible to avoid this.

like image 148
Markus Avatar answered Sep 27 '22 22:09

Markus