OpenOCD
time_support_common.c
Go to the documentation of this file.
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 
3 /***************************************************************************
4  * Copyright (C) 2006 by Dominic Rath *
5  * Dominic.Rath@gmx.de *
6  * *
7  * Copyright (C) 2007,2008 Øyvind Harboe *
8  * oyvind.harboe@zylin.com *
9  * *
10  * Copyright (C) 2008 by Spencer Oliver *
11  * spen@spen-soft.co.uk *
12  * *
13  * Copyright (C) 2026 by Grant Ramsay *
14  * grant.ramsay@hotmail.com *
15  ***************************************************************************/
16 
17 #ifdef HAVE_CONFIG_H
18 #include "config.h"
19 #endif
20 
21 #include "time_support.h"
22 
23 #ifdef _WIN32
24 #include <windows.h>
25 #endif
26 
27 /* simple and low overhead fetching of ms counter. Use only
28  * the difference between ms counters returned from this fn.
29  * Use QueryPerformanceCounter for Windows, else
30  * clock_gettime with CLOCK_MONOTONIC_RAW if available, else
31  * clock_gettime with CLOCK_MONOTONIC if available, else
32  * fallback to gettimeofday (susceptible to NTP adjustments)
33  */
34 int64_t timeval_ms(void)
35 {
36 #ifdef _WIN32
37  static LARGE_INTEGER frequency;
38  LARGE_INTEGER now;
39  // frequency is static and only read once on the first call
40  if (frequency.QuadPart == 0 && !QueryPerformanceFrequency(&frequency))
41  return -1;
42  if (!QueryPerformanceCounter(&now))
43  return -1;
44  return (now.QuadPart * 1000) / frequency.QuadPart;
45 #elif defined(HAVE_CLOCK_GETTIME)
46 #ifdef CLOCK_MONOTONIC_RAW
47  clockid_t clk_id = CLOCK_MONOTONIC_RAW;
48 #else
49  clockid_t clk_id = CLOCK_MONOTONIC;
50 #endif
51  struct timespec now;
52  int retval = clock_gettime(clk_id, &now);
53  if (retval < 0)
54  return retval;
55  return (int64_t)now.tv_sec * 1000 + now.tv_nsec / 1000000;
56 #else
57  struct timeval now;
58  int retval = gettimeofday(&now, NULL);
59  if (retval < 0)
60  return retval;
61  return (int64_t)now.tv_sec * 1000 + now.tv_usec / 1000;
62 #endif
63 }
int64_t timeval_ms(void)
#define NULL
Definition: usb.h:16