Getting elapsed time since the start of the process

I need a way to get the elapsed time (wall clock time) from the moment the program was launched so that it was stable for users interacting with the system clock.

On Windows, the non-standard implementation of clock () does not do the trick, since it seems to work just by calculating the difference with the time selected at startup, so that I get negative values ​​if I “move the clock backward”.

On UNIX, the / getrusage clock refers to system time, while using a function such as gettimeofday to select timestamps has the same problem as using a clock in windows.

I am not interested in accuracy, and I hacked into the solution, having a half second timer rotating in the background, counteracting the clock when it happens (if the difference between the sampling time and the expected value exceeds 1 second, I use the expected timer for a new baseline), but I think there should be a better way.

+4
source share
6 answers

I think you can always start some kind of timer. For example, under Linux, a thread that will have a loop like this:

static void timer_thread(void * arg) { struct timespec delay; unsigned int msecond_delay = ((app_state_t*)arg)->msecond_delay; delay.tv_sec = 0; delay.tv_nsec = msecond_delay * 1000000; while(1) { some_global_counter_increment(); nanosleep(&delay, NULL); } } 

Where app_state_t is the structure of the application of your choice, you have saved the variables. If you want to prevent falsification, you must be sure that no one killed your thread.

+2
source

I don’t think you will find a cross-platform way to do this.

On Windows, you need GetTickCount (or maybe QueryPerformanceCounter and QueryPerformanceFrequency for a high-resolution timer). I have no experience with Linux, but a google search gave me clock_gettime .

+1
source

For POSIX, use clock_gettime() with CLOCK_MONOTONIC .

+1
source

Wall time can be calculated by calling time () .

0
source

If you have a network connection, you can always get the time from the NTP server. Obviously, this will not affect the local clock.

-1
source

/ proc / uptime on linux supports the number of seconds that the system has been busy (and the number of seconds that it has been idle) that should not be affected by changes in the clock, since it is supported by a system interrupt (jiffies / HZ). Perhaps windows have something similar?

-1
source

Source: https://habr.com/ru/post/1277721/


All Articles