How to get current time in Csound in k-rate?

Dear Csounders!

Is there a way to get current time in Csound in k-rate? So to say, a k-rate Csound opcode alternative to i.e. std::chrono::system_clock::now().

I need to make timestamps in order to synchronize csound output later with some other signals.

Here (Absolute time at k-rate) is described one (nice and pragmatic) way of doing that but times opcode gives precision in seconds and I need milliseconds.

Another way would be to simply count k-cycles, i.e. using timeinstk but here I need to relay that audio card/audio callback is almost perfectly punctual and doesn’t drift much with the time i.e. if recording lasts for 2 hours or more.


I think timeinstk is your best option. There shouldn’t be any drift at all. You could also write a simple UDO to count samples. Set ksmps to 1, add a k-rate counter, divide the counter by sr and multiply by 0.001 to get time in milliseconds. But you shouldn’t do a direct comparisons to the time, for example:

if timeUDO() == 5000 do
    //do some on 5 seconds

The timeUDO might never return 5000 due to rounding issues. If you can work on the sample level rather than time then you’ll get much better resolution. After all, there are only 1000 milliseconds in a second, but there are typically 44+ thousand samples in a second.

If you want to mark something as close to 5 seconds as possible, you could do it like this:

 if timeUDO() > 5000 
    /* do something on 5 seconds and set some kind of flag
    so this code doesn't get hit again */

I don’t know if that’s helpful at all, but good luck with your work.

1 Like

Thanks @Rory. It is very helpful. I will test it :beers: