4

I need a way to get the elapsed time (wall-clock time) since a program started, in a way that is resilient to users meddling with the system clock.

On windows, the non standard clock() implementation doesn't do the trick, as it appears to work just by calculating the difference with the time sampled at start up, so that I get negative values if I "move the clock hands back".

On UNIX, clock/getrusage refer to system time, whereas using function such as gettimeofday to sample timestamps has the same problem as using clock on windows.

I'm not really interested in precision, and I've hacked a solution by having a half a second resolution timer spinning in the background countering the clock skews when they happen (if the difference between the sampled time and the expected exceeds 1 second i use the expected timer for the new baseline) but I think there must be a better way.

4

6 回答 6

2

我想你总是可以启动某种计时器。例如在 Linux 下,一个线程会有这样的循环:

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);
        }
}

如果app_state_t您存储变量,您选择的应用程序结构在哪里。如果你想防止篡改,你需要确保没有人杀死你的线程

于 2008-10-14T15:26:34.977 回答
2

对于 POSIX,使用clock_gettime()with CLOCK_MONOTONIC

于 2009-05-01T17:58:58.303 回答
1

我不认为你会找到一种跨平台的方式来做到这一点。

在 Windows 上,您需要的是GetTickCount(或者可能是高分辨率计时器的QueryPerformanceCounterQueryPerformanceFrequency )。我在 Linux 上没有这方面的经验,但在谷歌上搜索给了我clock_gettime

于 2008-10-14T11:56:11.250 回答
0

挂钟时间可以通过time()调用来计算。

于 2008-10-14T12:37:04.927 回答
-1

If you have a network connection, you can always acquire the time from an NTP server. This will obviously not be affected in any the local clock.

于 2008-10-14T10:37:21.067 回答
-1

Linux 上的 /proc/uptime 维护系统已启动的秒数(以及空闲的秒数),它应该不受时钟更改的影响,因为它由系统中断(jiffies / HZ)维护. 也许Windows有类似的东西?

于 2008-10-14T13:45:43.777 回答