Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to repeat the function N times per second?

Tags:

go

How to repeat the function N times per second in Go?

I can:

N := 30 //Repeat 30 times per second
for {
    //Do something
    time.Sleep(time.Second * time.Duration(N))
}

But that just makes the intervals between repetitions

like image 941
Maxim Lis Avatar asked Jan 08 '23 00:01

Maxim Lis


1 Answers

There are two options, neither will get you a guaranteed x times per second.

  • Set N not to 30 but 1/30. Thus the sleep will be for 1/30th of a second.
  • Have an internal for-loop that loops 30 times and executes your 'do something', and then on exit you hit the statement that sleeps for a second.

Option One:

N := 30 //Repeat 30 times per second
for {
    //Do something
    time.Sleep(time.Duration(1e9 / N))  //time.second constant unnecessary (see kostya comments)
}

Option Two:

N := 1  //Sleep duration of one second
for {
    for i := 1;  i<=30; i++ {
        //Do something
    }
    time.Sleep(time.Second * time.Duration(N))
}

Note that in option two, everything happens all at once, and then you wait a second. The first option will space out the do something across the second. Because of timing in computers this won't be precise: sleep cannot guarantee it will wake up precisely when you expect.

like image 92
Nathaniel Ford Avatar answered Jan 15 '23 21:01

Nathaniel Ford