登录
首页 >  Golang >  Go问答

增加时间行情程序的单调性

来源:stackoverflow

时间:2024-02-12 19:21:22 463浏览 收藏

从现在开始,我们要努力学习啦!今天我给大家带来《增加时间行情程序的单调性》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!

问题内容

我的 golang 程序中有几个 goroutine,其中一个有一个无限循环,运行 20 毫秒。在这个 goroutine 内部,没有繁重的操作和共享数据,但是,股票行情指示器无法准确工作 - 响应时间为 15 到 40 毫秒,我需要尽可能准确到 20 毫秒。我认为这是由于竞争与其他协程。股票代码程序是:

func (v *vocoderfile) sendaudioloop() {
    targetinterval := 20 * time.millisecond
    for {

        starttime := time.now()

        // some procedure.....

        elapsed := time.since(starttime)
        if elapsed < targetinterval {
            time.sleep(targetinterval - elapsed)
        }
    }
}

我还测试了其他变体 - 类似的结果:

func (v *vocoderFile) sendAudioLoop() {
    ticker := time.NewTicker(20 * time.Millisecond)
    for {
        <-ticker.C

        // Some procedure.....
    }
}

如何使 sendaudioloop 工作更加单调?


正确答案


我认为您需要为自己的程序时序需求建立可接受的下限和上限,然后进行过采样并测试正确的间隔:

const (
    lower = 19_900 * time.microsecond
    upper = 20_100 * time.microsecond
)

// pulse does something every 20ms +/-.1ms
func pulse() {
    var (
        last    = time.now()
        elapsed time.duration
    )

    ticker := time.newticker(500 * time.microsecond)
    for now := range ticker.c {
        elapsed = now.sub(last)
        if elapsed > lower {
            // some procedure...
            last = now
        }
    }
}

尽管自动收报机的 500μs 周期比 +/- 100μs 的裕度要粗,但我在 1000 个脉冲(20 秒)的测试运行中没有看到间隔错误。

我对 go 的调度程序和计时的内部原理了解不多。我读了 this issue on the performance of Sleep and Ticker,这给了我一些关于性能和模式的想法。这个 so,Sleep() or Timer(), Go idiomatic?,给了我一个想法,我可能应该只使用 timer。

我已经包含了一个完整的程序来生成大约 1000 个测试脉冲和一些统计数据,例如:

...5s elapsed
...5s elapsed
...5s elapsed
...5s elapsed
1000 pulses: 19.941ms...20.061916ms

有时(例如在运行中启动 macos 中的活动监视器),我的系统承受的压力足以导致延迟 3 倍:

...
9 too-long pulses:
  20.173042ms
  20.294166ms
  20.314125ms
  20.333667ms
  20.611917ms
  21.762083ms
  22.614583ms
  22.809292ms
  58.68725ms

不过,通常情况下,即使 cpu 固定在 100%,ticker 也在我的 100μs 范围内。

func main() {
    done := time.After(20*time.Second + 1*time.Millisecond) // run time limit
    tickTock := time.NewTicker(5 * time.Second)             // incremental print msg

    go randomWork() // pegs CPU at about 100%

    chP := make(chan time.Duration)
    go pulse(chP)

    pulses := make([]time.Duration, 0)
loop:
    for {
        select {
        case d := <-chP:
            pulses = append(pulses, d)
        case <-tickTock.C:
            fmt.Println("...5s elapsed")
        case <-done:
            break loop
        }
    }

    printStats(pulses)
}

const (
    lower = 19_900 * time.Microsecond
    upper = 20_100 * time.Microsecond
)

// pulse does something every 20ms +/-.1ms
func pulse(ch chan<- time.Duration) {
    var (
        last    = time.Now()
        elapsed time.Duration
    )

    ticker := time.NewTicker(500 * time.Microsecond)
    for now := range ticker.C {
        elapsed = now.Sub(last)
        if elapsed > lower {
            // Some procedure...
            ch <- elapsed
            last = now
        }
    }
}

func randomWork() {
    for {
        x := 0
        for i := 0; i < rand.Intn(1e7); i++ {
            x = i
        }
        x = x // silence "unused x" error
    }
}

func printStats(pulses []time.Duration) {
    sort.Slice(pulses, func(i, j int) bool { return pulses[i] < pulses[j] })

    tooShort := make([]time.Duration, 0)
    tooLong := make([]time.Duration, 0)
    for _, d := range pulses {
        if d < lower {
            tooShort = append(tooShort, d)
        }
        if d > upper {
            tooLong = append(tooLong, d)
        }
    }

    fmt.Printf("%d pulses: %v...%v\n", len(pulses), pulses[0], pulses[len(pulses)-1])

    if len(tooShort) > 0 {
        fmt.Printf("%d too-short pulses:\n", len(tooShort))
        for _, d := range tooShort {
            fmt.Printf("  %v\n", d)
        }
    }

    if len(tooLong) > 0 {
        fmt.Printf("%d too-long pulses:\n", len(tooLong))
        for _, d := range tooLong {
            fmt.Printf("  %v\n", d)
        }
    }
}

到这里,我们也就讲完了《增加时间行情程序的单调性》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>