I need to calculate time difference in milliseconds on Linux (Ubuntu 14).
It needs to be independent from system time because the application may change it during the execution (it sets system time according to the data received from GPS).
I've checked the clock function and it doesn't work for us because it returns the processor time consumed by the program and we need the real time.
The sysinfo (as mentioned in this question) return seconds since boot and, again, we need milliseconds.
And reading from /proc/uptime (as mentioned in this question) seem to be slow according to our tests (considering we want milliseconds and this function is called repeatedly).
We can use C++11, but I think std::chrono is related to system time also (correct me if I'm wrong).
Is there any other method to accomplish this?
Our Performance Test (for /proc/uptime comparison), 1 million of repeated calls:
gettimeofday:
(not what we need since it depends on the system time)
#include <sys/time.h>
unsigned int GetMs(){
unsigned int ret = 0;
timeval ts;
gettimeofday(&ts,0);
static long long inici = 0;
if (inici==0){
inici = ts.tv_sec;
}
ts.tv_sec -= inici;
ret = (ts.tv_sec*1000 + (ts.tv_usec/1000));
return ret;
}
clock:
(not valid, returns ticks used by the application, not real time)
#include <time.h>
unsigned int GetMs(){
unsigned int ret = 0;
clock_t t;
t = clock();
ret = t / 1000;
return ret;
}
uptime:
#include <fstream>
unsigned int GetMs(){
unsigned int ret = 0;
double uptime_seconds;
if (std::ifstream("/proc/uptime", std::ios::in) >> uptime_seconds) {
ret = (int) (1000 * uptime_seconds);
}
}
Results:
- gettimeofday: 31 milliseconds
- clock: 153 milliseconds
- uptime: 6005 milliseconds