Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fastest way to get the current time in C++11?

Context: I'm writing a high performance C++11 application, one part of it is to remove inactive connections. For that, I'm storing a "last activity" timestamp in my connection object, which I update when an action is taken. I then have a timer which runs every few seconds, loops over all sessions, and removes inactive ones.

Currently I'm using this code to get the current timestamp:

timestamp = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count()

I'm wondering if there is any faster way to do it? By faster I mean the performance of getting the timestamp itself, not the resolution of the timestamp.

The resolution is not really important for my specific application, it could go as low as a second. Also, utc/local doesn't matter, I am only using the timestamp to compare it to other timestamps, accquired by the same method.

I would like to keep it cross-platform, but platform-specific optimizations with conditional compilation are also welcome.

like image 542
Gediminas Masaitis Avatar asked Oct 16 '17 13:10

Gediminas Masaitis


1 Answers

If performance is really an issue, and accuracy isn't, then you might not need to use a timestamp at all. Rather just keep a counter for each connection, and whenever activity occurs for the connection, reset the counter to zero. Whenever your timer goes off, have it increment the counter for each connection, and disconnect any connection whose counter value rises above (N) (for whatever value of N you find works best)

like image 176
Jeremy Friesner Avatar answered Oct 15 '22 18:10

Jeremy Friesner