Does std::time::Instant() do a syscall ?
What is the cheapest 'clock' we can get if we only need millisecond level accuracy.
XY problem: doing some work involving rate limiting packets. Thus, looking for an ultra cheap solution that can be called for every packet.
It depends on your operating system. On modern Linux, it goes through the VDSO and does not make a syscall. You could use Criterion to benchmark the performance of Instant::now().
Do you need a clock call per packet then? Other options might be things like a timer that resets limits every N milliseconds.
For simplicitly, I'll assume that you've mapped those connections to continuous numbers in
0..10000. I'll leave "does that count as an active connection, and what number is it" to you.
One approach that comes to mind would be to have two
[AtomicU8; 10000] buffers and an atomic pointer. Every second, based on a 1-second timer, you flip the pointer to the other buffer, wait a few dozen ms (so probably nothing is looking at the old one) and zero out the now-unused buffer.
Then when a request comes in, you atomically read the pointer, do an atomic add-one (being careful about overflow) to get which packet-per-second it is, and use that in your throttling logic.
That means it's usually just two derefs -- to things that are likely in cache -- and an increment, which is going to be about as cheap as you get for something that needs to keep state.
EDIT: Oh, you deleted the post to which I was replying