More accurate ticker than time.NewTicker in go on macOS

Viewed 350

I am writing code to control external LEDs over UDP, and need to keep a frame rate (e.g. 60Hz) that is as constant as possible. Too much jitter will look bad. I've written a simple test using time.NewTicker and the results are not ideal. I'm wondering if there is a different way to execute code on a more accurate interval. This test was run on macOS, but needs to run on Windows and Linux too. For what it's worth, it needs to sync to audio, so maybe there is an audio ticker API on each OS it could potentially sync with?

package main

import (
    "encoding/csv"
    "fmt"
    "log"
    "os"
    "strconv"
    "time"
)

var f *os.File
var testTimeSeconds = 30

func appendToCsv(t time.Time) {

    w := csv.NewWriter(f)
    defer w.Flush()

    records := []string{strconv.FormatInt(t.UnixMicro(), 10)}
    w.Write(records)
}

func init() {
    var err error
    f, err = os.Create("newTicker.csv")
    if err != nil {
        log.Fatal(err)
    }

    w := csv.NewWriter(f)
    defer w.Flush()

    records := []string{"timestamps"}
    w.Write(records)
}

func main() {
    usPerFrame := 16666
    ticker := time.NewTicker(time.Duration(usPerFrame) * time.Microsecond)
    defer ticker.Stop()
    done := make(chan bool)
    go func() {
        time.Sleep(time.Duration(testTimeSeconds) * time.Second)
        done <- true
    }()
    for {
        select {
        case <-done:
            fmt.Println("Done!")
            return
        case t := <-ticker.C:
            appendToCsv(t)
        }
    }
}

enter image description here

UPDATE: I ran another test comparing the first method with the method in @jochen's answer, still not very accurate.

sleeptimer

1 Answers

One idea would be to just use time.Sleep() instead of a ticker. This takes the channel send/receive out of the loop and may lead to more accurate timing. To do this, you could run a function like the following in a separate goroutine:

func ticker(step time.Duration, done <-chan struct{}) {
        next := time.Now().Add(step)
        for {
                time.Sleep(time.Until(next))
                appendToCsv(time.Now())

                select { // check whether `done` was closed
                case <-done:
                        return
                default:
                        // pass
                }

                next = next.Add(step)
        }
}
Related