简体   繁体   English

如何使用 ANSI C 以毫秒为单位测量时间?

[英]How to measure time in milliseconds using ANSI C?

Using only ANSI C, is there any way to measure time with milliseconds precision or more?仅使用 ANSI C,有没有办法以毫秒或更高的精度测量时间? I was browsing time.h but I only found second precision functions.我正在浏览 time.h,但我只找到了二阶精度函数。

There is no ANSI C function that provides better than 1 second time resolution but the POSIX function gettimeofday provides microsecond resolution.没有提供优于 1 秒时间分辨率的 ANSI C 函数,但 POSIX 函数gettimeofday提供微秒分辨率。 The clock function only measures the amount of time that a process has spent executing and is not accurate on many systems.时钟函数仅测量进程执行所花费的时间量,在许多系统上并不准确。

You can use this function like this:你可以像这样使用这个函数:

struct timeval tval_before, tval_after, tval_result;

gettimeofday(&tval_before, NULL);

// Some code you want to time, for example:
sleep(1);

gettimeofday(&tval_after, NULL);

timersub(&tval_after, &tval_before, &tval_result);

printf("Time elapsed: %ld.%06ld\n", (long int)tval_result.tv_sec, (long int)tval_result.tv_usec);

This returns Time elapsed: 1.000870 on my machine.这将返回Time elapsed: 1.000870在我的机器上。

#include <time.h>
clock_t uptime = clock() / (CLOCKS_PER_SEC / 1000);

I always use the clock_gettime() function, returning time from the CLOCK_MONOTONIC clock.我总是使用clock_gettime() 函数,从CLOCK_MONOTONIC 时钟返回时间。 The time returned is the amount of time, in seconds and nanoseconds, since some unspecified point in the past, such as system startup of the epoch.返回的时间是从过去某个未指定点(例如 epoch 的系统启动)开始的时间量,以秒和纳秒为单位。

#include <stdio.h>
#include <stdint.h>
#include <time.h>

int64_t timespecDiff(struct timespec *timeA_p, struct timespec *timeB_p)
{
  return ((timeA_p->tv_sec * 1000000000) + timeA_p->tv_nsec) -
           ((timeB_p->tv_sec * 1000000000) + timeB_p->tv_nsec);
}

int main(int argc, char **argv)
{
  struct timespec start, end;
  clock_gettime(CLOCK_MONOTONIC, &start);

  // Some code I am interested in measuring 

  clock_gettime(CLOCK_MONOTONIC, &end);

  uint64_t timeElapsed = timespecDiff(&end, &start);
}

Implementing a portable solution实施便携式解决方案

As it was already mentioned here that there is no proper ANSI solution with sufficient precision for the time measurement problem, I want to write about the ways how to get a portable and, if possible, a high-resolution time measurement solution.正如这里已经提到的那样,对于时间测量问题没有足够精确的适当 ANSI 解决方案,我想写下如何获得便携式和高分辨率时间测量解决方案的方法,如果可能的话。

Monotonic clock vs. time stamps单调时钟与时间戳

Generally speaking there are two ways of time measurement:一般而言,时间测量有两种方式:

  • monotonic clock;单调时钟;
  • current (date)time stamp.当前(日期)时间戳。

The first one uses a monotonic clock counter (sometimes it is called a tick counter) which counts ticks with a predefined frequency, so if you have a ticks value and the frequency is known, you can easily convert ticks to elapsed time.第一个使用单调时钟计数器(有时称为滴答计数器),它以预定义的频率计算滴答,因此如果您有滴答值并且频率已知,您可以轻松地将滴答转换为经过的时间。 It is actually not guaranteed that a monotonic clock reflects the current system time in any way, it may also count ticks since a system startup.实际上并不能保证单调时钟以任何方式反映当前系统时间,它也可能计算自系统启动以来的滴答数。 But it guarantees that a clock is always run up in an increasing fashion regardless of the system state.但它保证无论系统状态如何,时钟始终以递增的方式运行。 Usually the frequency is bound to a hardware high-resolution source, that's why it provides a high accuracy (depends on hardware, but most of the modern hardware has no problems with high-resolution clock sources).通常频率与硬件高分辨率源绑定,这就是它提供高精度的原因(取决于硬件,但大多数现代硬件对高分辨率时钟源没有问题)。

The second way provides a (date)time value based on the current system clock value.第二种方式提供基于当前系统时钟值的(日期)时间值。 It may also have a high resolution, but it has one major drawback: this kind of time value can be affected by different system time adjustments, ie time zone change, daylight saving time (DST) change, NTP server update, system hibernation and so on.它也可能具有高分辨率,但它有一个主要缺点:这种时间值会受到不同系统时间调整的影响,即时区更改、夏令时 (DST) 更改、NTP 服务器更新、系统休眠等上。 In some circumstances you can get a negative elapsed time value which can lead to an undefined behavior.在某些情况下,您可能会得到一个负的经过时间值,这可能会导致未定义的行为。 Actually this kind of time source is less reliable than the first one.实际上这种时间源不如第一种可靠。

So the first rule in time interval measuring is to use a monotonic clock if possible.所以时间间隔测量的第一条规则是尽可能使用单调时钟。 It usually has a high precision, and it is reliable by design.它通常具有很高的精度,并且在设计上是可靠的。

Fallback strategy回退策略

When implementing a portable solution it is worth to consider a fallback strategy: use a monotonic clock if available and fallback to time stamps approach if there is no monotonic clock in the system.在实现便携式解决方案时,值得考虑回退策略:如果可用,请使用单调时钟,如果系统中没有单调时钟,则回退到时间戳方法。

Windows窗户

There is a great article called Acquiring high-resolution time stamps on MSDN about time measurement on Windows which describes all the details you may need to know about software and hardware support.在 MSDN 上有一篇名为Acquiring high-resolution time stamps on Windows 时间测量的很棒的文章,它描述了您可能需要了解的有关软件和硬件支持的所有详细信息。 To acquire a high precision time stamp on Windows you should:要在 Windows 上获取高精度时间戳,您应该:

  • query a timer frequency (ticks per second) with QueryPerformanceFrequency :使用QueryPerformanceFrequency查询计时器频率(每秒滴答数):

     LARGE_INTEGER tcounter; LARGE_INTEGER freq; if (QueryPerformanceFrequency (&tcounter) != 0) freq = tcounter.QuadPart;

    The timer frequency is fixed on the system boot so you need to get it only once.计时器频率在系统启动时是固定的,因此您只需获取一次。

  • query the current ticks value with QueryPerformanceCounter :使用QueryPerformanceCounter查询当前刻度值:

     LARGE_INTEGER tcounter; LARGE_INTEGER tick_value; if (QueryPerformanceCounter (&tcounter) != 0) tick_value = tcounter.QuadPart;
  • scale the ticks to elapsed time, ie to microseconds:将刻度缩放到经过的时间,即微秒:

     LARGE_INTEGER usecs = (tick_value - prev_tick_value) / (freq / 1000000);

According to Microsoft you should not have any problems with this approach on Windows XP and later versions in most cases.根据微软的说法,在大多数情况下,这种方法在 Windows XP 和更高版本上应该不会有任何问题。 But you can also use two fallback solutions on Windows:但您也可以在 Windows 上使用两种后备解决方案:

  • GetTickCount provides the number of milliseconds that have elapsed since the system was started. GetTickCount提供自系统启动以来经过的毫秒数。 It wraps every 49.7 days, so be careful in measuring longer intervals.它每 49.7 天包装一次,因此在测量更长的间隔时要小心。
  • GetTickCount64 is a 64-bit version of GetTickCount , but it is available starting from Windows Vista and above. GetTickCount64是64位版本的GetTickCount ,但它是从Windows Vista及更高版本开始。

OS X (macOS) OS X (macOS)

OS X (macOS) has its own Mach absolute time units which represent a monotonic clock. OS X (macOS) 有自己的马赫绝对时间单位,代表单调时钟。 The best way to start is the Apple's article Technical Q&A QA1398: Mach Absolute Time Units which describes (with the code examples) how to use Mach-specific API to get monotonic ticks.最好的开始方法是 Apple 的文章Technical Q&A QA1398: Mach Absolute Time Units ,它描述了(带有代码示例)如何使用 Mach 特定的 API 来获取单调滴答声。 There is also a local question about it called clock_gettime alternative in Mac OS X which at the end may leave you a bit confused what to do with the possible value overflow because the counter frequency is used in the form of numerator and denominator.还有一个关于它的本地问题, 在 Mac OS X 中称为clock_gettime 替代方案,最后可能会让您有点困惑如何处理可能的值溢出,因为计数器频率以分子和分母的形式使用。 So, a short example how to get elapsed time:因此,一个如何获得经过时间的简短示例:

  • get the clock frequency numerator and denominator:获取时钟频率分子和分母:

     #include <mach/mach_time.h> #include <stdint.h> static uint64_t freq_num = 0; static uint64_t freq_denom = 0; void init_clock_frequency () { mach_timebase_info_data_t tb; if (mach_timebase_info (&tb) == KERN_SUCCESS && tb.denom != 0) { freq_num = (uint64_t) tb.numer; freq_denom = (uint64_t) tb.denom; } }

    You need to do that only once.你只需要这样做一次。

  • query the current tick value with mach_absolute_time :使用mach_absolute_time查询当前刻度值:

     uint64_t tick_value = mach_absolute_time ();
  • scale the ticks to elapsed time, ie to microseconds, using previously queried numerator and denominator:使用先前查询的分子和分母将刻度缩放到经过的时间,即微秒:

     uint64_t value_diff = tick_value - prev_tick_value; /* To prevent overflow */ value_diff /= 1000; value_diff *= freq_num; value_diff /= freq_denom;

    The main idea to prevent an overflow is to scale down the ticks to desired accuracy before using the numerator and denominator.防止溢出的主要思想是在使用分子和分母之前将刻度按比例缩小到所需的精度。 As the initial timer resolution is in nanoseconds, we divide it by 1000 to get microseconds.由于初始计时器分辨率以纳秒为单位,我们将其除以1000以获得微秒。 You can find the same approach used in Chromium's time_mac.c .您可以找到 Chromium 的time_mac.c 中使用的相同方法。 If you really need a nanosecond accuracy consider reading the How can I use mach_absolute_time without overflowing?如果您真的需要纳秒精度,请考虑阅读如何使用 mach_absolute_time 而不会溢出? . .

Linux and UNIX Linux 和 UNIX

The clock_gettime call is your best way on any POSIX-friendly system.在任何 POSIX 友好系统上, clock_gettime调用是您最好的方法。 It can query time from different clock sources, and the one we need is CLOCK_MONOTONIC .它可以从不同的时钟源查询时间,我们需要的是CLOCK_MONOTONIC Not all systems which have clock_gettime support CLOCK_MONOTONIC , so the first thing you need to do is to check its availability:并非所有具有clock_gettime系统都支持CLOCK_MONOTONIC ,因此您需要做的第一件事是检查其可用性:

  • if _POSIX_MONOTONIC_CLOCK is defined to a value >= 0 it means that CLOCK_MONOTONIC is avaiable;如果_POSIX_MONOTONIC_CLOCK定义为>= 0的值,则表示CLOCK_MONOTONIC可用;
  • if _POSIX_MONOTONIC_CLOCK is defined to 0 it means that you should additionally check if it works at runtime, I suggest to use sysconf :如果_POSIX_MONOTONIC_CLOCK被定义为0意味着你应该额外检查它是否在运行时工作,我建议使用sysconf

     #include <unistd.h> #ifdef _SC_MONOTONIC_CLOCK if (sysconf (_SC_MONOTONIC_CLOCK) > 0) { /* A monotonic clock presents */ } #endif
  • otherwise a monotonic clock is not supported and you should use a fallback strategy (see below).否则不支持单调时钟,您应该使用回退策略(见下文)。

Usage of clock_gettime is pretty straight forward: clock_gettime使用非常简单:

  • get the time value:获取时间值:

     #include <time.h> #include <sys/time.h> #include <stdint.h> uint64_t get_posix_clock_time () { struct timespec ts; if (clock_gettime (CLOCK_MONOTONIC, &ts) == 0) return (uint64_t) (ts.tv_sec * 1000000 + ts.tv_nsec / 1000); else return 0; }

    I've scaled down the time to microseconds here.我已经将时间缩减到微秒。

  • calculate the difference with the previous time value received the same way:以同样的方式计算与之前接收到的时间值的差异:

     uint64_t prev_time_value, time_value; uint64_t time_diff; /* Initial time */ prev_time_value = get_posix_clock_time (); /* Do some work here */ /* Final time */ time_value = get_posix_clock_time (); /* Time difference */ time_diff = time_value - prev_time_value;

The best fallback strategy is to use the gettimeofday call: it is not a monotonic, but it provides quite a good resolution.最好的回退策略是使用gettimeofday调用:它不是单调的,但它提供了很好的解决方案。 The idea is the same as with clock_gettime , but to get a time value you should:这个想法与clock_gettime相同,但要获得时间值,您应该:

#include <time.h>
#include <sys/time.h>
#include <stdint.h>

uint64_t get_gtod_clock_time ()
{
    struct timeval tv;

    if (gettimeofday (&tv, NULL) == 0)
        return (uint64_t) (tv.tv_sec * 1000000 + tv.tv_usec);
    else
        return 0;
}

Again, the time value is scaled down to microseconds.同样,时间值缩小到微秒。

SGI IRIX SGI IRIX

IRIX has the clock_gettime call, but it lacks CLOCK_MONOTONIC . IRIXclock_gettime调用,但缺少CLOCK_MONOTONIC Instead it has its own monotonic clock source defined as CLOCK_SGI_CYCLE which you should use instead of CLOCK_MONOTONIC with clock_gettime .相反,它有自己定义为CLOCK_SGI_CYCLE的单调时钟源,您应该使用它来代替CLOCK_MONOTONICclock_gettime

Solaris and HP-UX Solaris 和 HP-UX

Solaris has its own high-resolution timer interface gethrtime which returns the current timer value in nanoseconds. Solaris 有自己的高分辨率计时器接口gethrtime ,它以纳秒为单位返回当前计时器值。 Though the newer versions of Solaris may have clock_gettime , you can stick to gethrtime if you need to support old Solaris versions.尽管较新版本的 Solaris 可能有clock_gettimegethrtime如果您需要支持旧的 Solaris 版本,则可以坚持使用gethrtime

Usage is simple:用法很简单:

#include <sys/time.h>

void time_measure_example ()
{
    hrtime_t prev_time_value, time_value;
    hrtime_t time_diff;

    /* Initial time */
    prev_time_value = gethrtime ();

    /* Do some work here */

    /* Final time */
    time_value = gethrtime ();

    /* Time difference */
    time_diff = time_value - prev_time_value;
}

HP-UX lacks clock_gettime , but it supports gethrtime which you should use in the same way as on Solaris. HP-UX 没有clock_gettime ,但它支持gethrtime ,您应该像在 Solaris 上一样使用它。

BeOS操作系统

BeOS also has its own high-resolution timer interface system_time which returns the number of microseconds have elapsed since the computer was booted. BeOS也有自己的高分辨率计时器接口system_time ,它返回计算机启动后经过的微秒数。

Example usage:用法示例:

#include <kernel/OS.h>

void time_measure_example ()
{
    bigtime_t prev_time_value, time_value;
    bigtime_t time_diff;

    /* Initial time */
    prev_time_value = system_time ();

    /* Do some work here */

    /* Final time */
    time_value = system_time ();

    /* Time difference */
    time_diff = time_value - prev_time_value;
}

OS/2操作系统/2

OS/2 has its own API to retrieve high-precision time stamps: OS/2有自己的 API 来检索高精度时间戳:

  • query a timer frequency (ticks per unit) with DosTmrQueryFreq (for GCC compiler):使用DosTmrQueryFreq (用于 GCC 编译器)查询计时器频率(每单位滴答数):

     #define INCL_DOSPROFILE #define INCL_DOSERRORS #include <os2.h> #include <stdint.h> ULONG freq; DosTmrQueryFreq (&freq);
  • query the current ticks value with DosTmrQueryTime :使用DosTmrQueryTime查询当前刻度值:

     QWORD tcounter; unit64_t time_low; unit64_t time_high; unit64_t timestamp; if (DosTmrQueryTime (&tcounter) == NO_ERROR) { time_low = (unit64_t) tcounter.ulLo; time_high = (unit64_t) tcounter.ulHi; timestamp = (time_high << 32) | time_low; }
  • scale the ticks to elapsed time, ie to microseconds:将刻度缩放到经过的时间,即微秒:

     uint64_t usecs = (prev_timestamp - timestamp) / (freq / 1000000);

Example implementation示例实现

You can take a look at the plibsys library which implements all the described above strategies (see ptimeprofiler*.c for details).您可以查看实现上述所有策略的plibsys库(有关详细信息,请参阅 ptimeprofiler*.c)。

timespec_get from C11来自 C11 的timespec_get

Returns up to nanoseconds, rounded to the resolution of the implementation.返回最多纳秒,四舍五入到实现的分辨率。

Looks like an ANSI ripoff from POSIX' clock_gettime .看起来像是来自 POSIX 的clock_gettime ANSI ripoff。

Example: a printf is done every 100ms on Ubuntu 15.10:示例:在 Ubuntu 15.10 上每 100 毫秒执行一次printf

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

static long get_nanos(void) {
    struct timespec ts;
    timespec_get(&ts, TIME_UTC);
    return (long)ts.tv_sec * 1000000000L + ts.tv_nsec;
}

int main(void) {
    long nanos;
    long last_nanos;
    long start;
    nanos = get_nanos();
    last_nanos = nanos;
    start = nanos;
    while (1) {
        nanos = get_nanos();
        if (nanos - last_nanos > 100000000L) {
            printf("current nanos: %ld\n", nanos - start);
            last_nanos = nanos;
        }
    }
    return EXIT_SUCCESS;
}

The C11 N1570 standard draft 7.27.2.5 "The timespec_get function says": C11 N1570 标准草案7.27.2.5 “timespec_get 函数说”:

If base is TIME_UTC, the tv_sec member is set to the number of seconds since an implementation defined epoch, truncated to a whole value and the tv_nsec member is set to the integral number of nanoseconds, rounded to the resolution of the system clock.如果 base 是 TIME_UTC,则 tv_sec 成员设置为自实现定义的纪元以来的秒数,截断为整数值,tv_nsec 成员设置为纳秒整数,四舍五入到系统时钟的分辨率。 (321) (321)

321) Although a struct timespec object describes times with nanosecond resolution, the available resolution is system dependent and may even be greater than 1 second. 321) 尽管 struct timespec 对象以纳秒分辨率描述时间,但可用分辨率取决于系统,甚至可能大于 1 秒。

C++11 also got std::chrono::high_resolution_clock : C++ Cross-Platform High-Resolution Timer C++11 也得到了std::chrono::high_resolution_clock : C++ Cross-Platform High-Resolution Timer

glibc 2.21 implementation glibc 2.21 实现

Can be found under sysdeps/posix/timespec_get.c as:可以在sysdeps/posix/timespec_get.c下找到:

int
timespec_get (struct timespec *ts, int base)
{
  switch (base)
    {
    case TIME_UTC:
      if (__clock_gettime (CLOCK_REALTIME, ts) < 0)
        return 0;
      break;

    default:
      return 0;
    }

  return base;
}

so clearly:这么清楚:

  • only TIME_UTC is currently supported目前仅支持TIME_UTC

  • it forwards to __clock_gettime (CLOCK_REALTIME, ts) , which is a POSIX API: http://pubs.opengroup.org/onlinepubs/9699919799/functions/clock_getres.html它转发到__clock_gettime (CLOCK_REALTIME, ts) ,这是一个POSIX API: http : __clock_gettime (CLOCK_REALTIME, ts)

    Linux x86-64 has a clock_gettime system call. Linux x86-64 有一个clock_gettime系统调用。

    Note that this is not a fail-proof micro-benchmarking method because:请注意,这不是防故障的微基准测试方法,因为:

    • man clock_gettime says that this measure may have discontinuities if you change some system time setting while your program runs. man clock_gettime表示如果您在程序运行时更改某些系统时间设置,则此度量可能会不连续。 This should be a rare event of course, and you might be able to ignore it.这当然应该是一个罕见的事件,您可能可以忽略它。

    • this measures wall time, so if the scheduler decides to forget about your task, it will appear to run for longer.这会测量墙上时间,因此如果调度程序决定忘记您的任务,它似乎会运行更长时间。

    For those reasons getrusage() might be a better better POSIX benchmarking tool, despite it's lower microsecond maximum precision.由于这些原因, getrusage()可能是更好的 POSIX 基准测试工具,尽管它的微秒最大精度较低。

    More information at: Measure time in Linux - time vs clock vs getrusage vs clock_gettime vs gettimeofday vs timespec_get?更多信息请访问: 在 Linux 中测量时间 - 时间 vs 时钟 vs getrusage vs clock_gettime vs gettimeofday vs timespec_get?

The best precision you can possibly get is through the use of the x86-only "rdtsc" instruction, which can provide clock-level resolution (ne must of course take into account the cost of the rdtsc call itself, which can be measured easily on application startup).您可能获得的最佳精度是通过使用仅 x86 的“rdtsc”指令,该指令可以提供时钟级分辨率(当然必须考虑 rdtsc 调用本身的成本,这可以在应用程序启动)。

The main catch here is measuring the number of clocks per second, which shouldn't be too hard.这里的主要问题是测量每秒的时钟数,这应该不会太难。

The accepted answer is good enough.But my solution is more simple.I just test in Linux, use gcc (Ubuntu 7.2.0-8ubuntu3.2) 7.2.0.接受的答案已经足够了。但我的解决方案更简单。我只是在 Linux 中测试,使用 gcc (Ubuntu 7.2.0-8ubuntu3.2) 7.2.0。

Alse use gettimeofday , the tv_sec is the part of second, and the tv_usec is microseconds , not milliseconds . ALSE使用gettimeofday ,所述tv_sec是第二部分,和所述tv_usec微秒,不毫秒

long currentTimeMillis() {
  struct timeval time;
  gettimeofday(&time, NULL);

  return time.tv_sec * 1000 + time.tv_usec / 1000;
}

int main() {
  printf("%ld\n", currentTimeMillis());
  // wait 1 second
  sleep(1);
  printf("%ld\n", currentTimeMillis());
  return 0;
 }

It print:它打印:

1522139691342
1522139692342 , exactly a second. 1522139692342 ,正好一秒钟。
^

As of ANSI/ISO C11 or later , you can use timespec_get() to obtain millisecond, microsecond, or nanosecond timestamps, like this:从 ANSI/ISO C11 或更高版本开始,您可以使用timespec_get()获取毫秒、微秒或纳秒时间戳,如下所示:

#include <time.h>

/// Convert seconds to milliseconds
#define SEC_TO_MS(sec) ((sec)*1000)
/// Convert seconds to microseconds
#define SEC_TO_US(sec) ((sec)*1000000)
/// Convert seconds to nanoseconds
#define SEC_TO_NS(sec) ((sec)*1000000000)

/// Convert nanoseconds to seconds
#define NS_TO_SEC(ns)   ((ns)/1000000000)
/// Convert nanoseconds to milliseconds
#define NS_TO_MS(ns)    ((ns)/1000000)
/// Convert nanoseconds to microseconds
#define NS_TO_US(ns)    ((ns)/1000)

/// Get a time stamp in milliseconds.
uint64_t millis()
{
    struct timespec ts;
    timespec_get(&ts, TIME_UTC);
    uint64_t ms = SEC_TO_MS((uint64_t)ts.tv_sec) + NS_TO_MS((uint64_t)ts.tv_nsec);
    return ms;
}

/// Get a time stamp in microseconds.
uint64_t micros()
{
    struct timespec ts;
    timespec_get(&ts, TIME_UTC);
    uint64_t us = SEC_TO_US((uint64_t)ts.tv_sec) + NS_TO_US((uint64_t)ts.tv_nsec);
    return us;
}

/// Get a time stamp in nanoseconds.
uint64_t nanos()
{
    struct timespec ts;
    timespec_get(&ts, TIME_UTC);
    uint64_t ns = SEC_TO_NS((uint64_t)ts.tv_sec) + (uint64_t)ts.tv_nsec;
    return ns;
}

// NB: for all 3 timestamp functions above: gcc defines the type of the internal
// `tv_sec` seconds value inside the `struct timespec`, which is used
// internally in these functions, as a signed `long int`. For architectures
// where `long int` is 64 bits, that means it will have undefined
// (signed) overflow in 2^64 sec = 5.8455 x 10^11 years. For architectures
// where this type is 32 bits, it will occur in 2^32 sec = 136 years. If the
// implementation-defined epoch for the timespec is 1970, then your program
// could have undefined behavior signed time rollover in as little as
// 136 years - (year 2021 - year 1970) = 136 - 51 = 85 years. If the epoch
// was 1900 then it could be as short as 136 - (2021 - 1900) = 136 - 121 =
// 15 years. Hopefully your program won't need to run that long. :). To see,
// by inspection, what your system's epoch is, simply print out a timestamp and
// calculate how far back a timestamp of 0 would have occurred. Ex: convert
// the timestamp to years and subtract that number of years from the present
// year.

For a much-more-thorough answer of mine, including with an entire timing library I wrote, see here: How to get a simple timestamp in C .有关我的更全面的答案,包括我编写的整个计时库,请参见此处: How to get a simple timestamp in C

@Ciro Santilli Путлер also presents a concise demo of C11's timespec_get() function here , which is how I first learned how to use that function. @Ciro Santilli Путлер 还在此处展示了 C11 的timespec_get() function 的简明演示,这是我第一次学习如何使用 function 的方式。

In my more-thorough answer , I explain that on my system, the best resolution possible is ~20ns , but the resolution is hardware-dependent and can vary from system to system.我更详尽的回答中,我解释说在我的系统上,可能的最佳分辨率是~20ns ,但该分辨率取决于硬件,并且可能因系统而异。

Under windows:在窗户下:

SYSTEMTIME t;
GetLocalTime(&t);
swprintf_s(buff, L"[%02d:%02d:%02d:%d]\t", t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM