You want to get a simple, sequential number from the system clock for timing purposes, or perhaps you want to get a guaranteed unique bit pattern for seeding a random number generator each time your application starts.
Sample code folder: Chapter 07\SystemTicks
Use the Now.Ticks property, which returns a long integer containing the number of 100-nanosecond intervals since midnight of January 1 in the year 1 AD.
The Ticks property is available on any Date variable, but it's most often used on the ever-changing Now property. Using Now.Ticks means the value returned will always be a unique Long value for every tick of the system clock, providing a good source for unique bit patterns.
Although Ticks appears to be accurate to the nearest 100 nanoseconds, it actually has much less resolution than expected. The following code shows how to access the Ticks property and, more importantly, demonstrates how many times the returned value of Ticks changes per second:
Dim lastTicks As Long Dim numTicks As Long Dim endTime As Date Dim results As String ' ----- Count the actual tick changes. endTime = Now.AddSeconds(1) Do If (Now.Ticks <> lastTicks) Then numTicks += 1 lastTicks = Now.Ticks End If Loop Until (Now > endTime) ' ----- Display the results. results = "Now.Ticks: " & Now.Ticks.ToString & vbNewLine & _ "Number of updates per second: " & numTicks.ToString MsgBox(results)
As shown in Figure 7-3, the value of the Ticks property changes only about 65 times per second. At the speed of today's computers, a lot of instructions can be processed in 1/65 of a second, making Ticks a poor choice for high-resolution timing.
Figure 7-3. Ticks represent short timing units, but they aren't updated very often
Ticks does have some good uses, but for timing that really is accurate to the nearest millisecond, consider using the new Stopwatch object, described later in this chapter.
Compare the results of this recipe with those of Recipe 7.4, which provides a much greater level of accuracy.