demo of sleep() for 1 sec excluding application loop time

Here you can share completed projects or parts of projects that may be useful to others. You may post files relevant to ZBasic - source code, schematics, etc.
Post Reply
stevech
Posts: 715
Joined: 22 February 2006, 20:56 PM

demo of sleep() for 1 sec excluding application loop time

Post by stevech »

This program prints the current time as
hh:mm:ss.s fractions of second

based on the the VM's RTC

it then sleeps for the remainder of one second.

That is, it sleeps for 1 second minus the time to compute and output to a queue the time string.

the sleep() function is used with some math to compute how long to sleep.

Simple but possibly useful example.

there's also an LED blinker: red/green/both, brief flashes once/sec
Attachments
sleepLessOverhead.pjt
(23 Bytes) Downloaded 3763 times
sleepLessOverhead.bas
(1.46 KiB) Downloaded 4190 times
dkinzer
Site Admin
Posts: 3120
Joined: 03 September 2005, 13:53 PM
Location: Portland, OR

Post by dkinzer »

That is a nice example. A couple of items to note:
1) The RTC tick frequency is available as an UnsignedInteger value Register.RTCTickFrequency. The value is returned by the VM at run time so that if future ZX models have a different RTC tick frequency your code will automatically adapt.

2) Another way to accomplish the same goal of equal interval execution is to use WaitForInterval(). A modified version of your code (omitting the unchanged parts) is shown below.

Code: Select all

Private intervalTaskStack(1 to 60) as Byte

sub main()
	Calltask blinkLED1, blinkled1stack
	CallTask IntervalTask, IntervalTaskStack
	Do
	Loop
end sub

Sub IntervalTask()
	Call SetInterval(1.0)  ' set a 1 second interval
	Do
		Dim h as Byte, m as Byte
		Dim sec as Single
		Dim s as string

		WaitForInterval(0)
		Call GetTime(h, m, sec)
		' make string like 00:00:00.0  time
		s=byteToAscii2(h) & ":" & byteToAscii2(m) & ":" & _
		byteToAscii2(cbyte(sec)) & "." & byteToAscii2(cbyte(100.0 * fraction(sec)))
		console.writeline(s)
	Loop
End Sub
- Don Kinzer
stevech
Posts: 715
Joined: 22 February 2006, 20:56 PM

Post by stevech »

Thanks for the kind words.
I (finally, as a noobie) interpreted SetInterval() and WaitForInterval() to say that the interval timer is global to all tasks, i.e., there is not a per-task interval counter. So my thinking in my code was to wait for the remainder of the time slot (one second in my example) to expire without a shared-use interval timer amongst all tasks. But I can see other situations where SetInterval as a global timer would be useful.

A nit pick: I might suggest taking a crack at rewording and clarifying the second paragraph if WaitForInterval() - it's kinda obtuse to me. I read these several times thinking the interval timer was per-task, since that's what I'm kind of used to in other OSes.
Post Reply