GTBecker
Joined: 18 Jan 2006
Posts: 457
Location: Cape Coral
|
|
Posted: 28 September 2009, 17:08 PM Post subject: High-resolution elapsed time function |
|
|
FWIW, here is an elapsed time function that, I believe, provides the best resolution possible in software timing. [InputCapture can be used for even higher resolution external events.]
The function ElapsedTime below provides the period since its previous execution. It uses Timer1, running here at maximum rate; the maximum measurable period at that rate is ~4.4mS. If a larger timer prescaler is used, the maximum measurable period will be correspondingly larger, at the cost of poorer resolution. The Main() sub here is a demonstration of its use, measuring the period and rate of the system-tick-timed Sleep() routine. Substituting Pause(1) for Sleep(1) shows the difference in Spread of the two.
| Code: | ' Test Timer1 as elapsed timer at highest resolution
' 2009-09-28 GTBecker
const Loops as integer = 1000
dim t0 as unsignedinteger
sub main()
dim i as integer, j as integer, x as single, strX as string, _
MaxX as single, MinX as single, MeanX as single, _
MinTime as integer, MaxTime as integer
call InitTimer1
for j = 1 to 8
MaxX = 0.0 : MinX = 5.0 : MeanX = 0.0
for i = 1 to Loops
call sleep(1)
x = ElapsedTime
if i <> 1 then ' ignore always-short first iteration
MaxX = max(MaxX, x)
MinX = min(MinX, x)
MeanX = MeanX + x
end if
next
MeanX = MeanX / csng(Loops - 1)
strX = "Max= " & cstr(MaxX) & "S, Min= " & cstr(MinX) & "S, Spread= " & _
cstr(MaxX - MinX) & "S, Mean(" & cstr(Loops) & ")= " & _
cstr(MeanX) & "S (" & cstr(1.0 / MeanX) & "Hz)"
console.writeline(strX)
next
end sub
function ElapsedTime() as single
dim t1 as unsignedinteger
t1 = makeword(register.TCNT1L, register.TCNT1H)
ElapsedTime = csng(abs(t1 - t0)) / 14745600.0 ' at ~14MHz, max period is ~4mS
t0 = t1 ' for next iteration
end function
sub InitTimer1()
register.TCCR1A = zx0000_0000 ' no output pin, just timer
register.TCCR1B = zx0000_0001 ' clk/1= 14745600 Hz, ~4.44mS max period
'register.TCCR1B = zx0000_0010 ' clk/8= 1843200 Hz, ~35.5mS
'register.TCCR1B = zx0000_0011 ' clk/64= 230400 Hz, ~284mS
'register.TCCR1B = zx0000_0100 ' clk/256= 57600 Hz, ~1.13S
'register.TCCR1B = zx0000_0101 ' clk/1024= 14400 Hz, ~4.55S
t0 = makeword(register.TCNT1L, register.TCNT1H)
end sub
|
|
|