clock.cpp 8.1 KB
Newer Older
Martin Sustrik's avatar
Martin Sustrik committed
1
/*
2
    Copyright (c) 2007-2016 Contributors as noted in the AUTHORS file
Martin Sustrik's avatar
Martin Sustrik committed
3

4
    This file is part of libzmq, the ZeroMQ core engine in C++.
Martin Sustrik's avatar
Martin Sustrik committed
5

6 7 8
    libzmq is free software; you can redistribute it and/or modify it under
    the terms of the GNU Lesser General Public License (LGPL) as published
    by the Free Software Foundation; either version 3 of the License, or
Martin Sustrik's avatar
Martin Sustrik committed
9 10
    (at your option) any later version.

11 12 13 14 15 16 17 18 19 20 21 22 23 24
    As a special exception, the Contributors give you permission to link
    this library with independent modules to produce an executable,
    regardless of the license terms of these independent modules, and to
    copy and distribute the resulting executable under terms of your choice,
    provided that you also meet, for each linked independent module, the
    terms and conditions of the license of that module. An independent
    module is a module which is not derived from or based on this library.
    If you modify this library, you must extend this exception to your
    version of the library.

    libzmq is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
    License for more details.
Martin Sustrik's avatar
Martin Sustrik committed
25

26
    You should have received a copy of the GNU Lesser General Public License
Martin Sustrik's avatar
Martin Sustrik committed
27 28 29
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

30
#include "precompiled.hpp"
Martin Sustrik's avatar
Martin Sustrik committed
31 32 33 34
#include "clock.hpp"
#include "likely.hpp"
#include "config.hpp"
#include "err.hpp"
35
#include "mutex.hpp"
Martin Sustrik's avatar
Martin Sustrik committed
36 37 38

#include <stddef.h>

39
#if defined _MSC_VER
40
#if defined _WIN32_WCE
boris@boressoft.ru's avatar
boris@boressoft.ru committed
41 42
#include <cmnintrin.h>
#else
43 44
#include <intrin.h>
#endif
boris@boressoft.ru's avatar
boris@boressoft.ru committed
45
#endif
46

Martin Sustrik's avatar
Martin Sustrik committed
47 48 49 50
#if !defined ZMQ_HAVE_WINDOWS
#include <sys/time.h>
#endif

51
#if defined HAVE_CLOCK_GETTIME || defined HAVE_GETHRTIME
52 53 54
#include <time.h>
#endif

55 56 57 58
#if defined ZMQ_HAVE_VXWORKS
#include "timers.h"
#endif

59
#if defined ZMQ_HAVE_OSX
60
int alt_clock_gettime (int clock_id, timespec *ts)
61 62 63
{
    clock_serv_t cclock;
    mach_timespec_t mts;
64
    host_get_clock_service (mach_host_self (), clock_id, &cclock);
65 66 67 68
    clock_get_time (cclock, &mts);
    mach_port_deallocate (mach_task_self (), cclock);
    ts->tv_sec = mts.tv_sec;
    ts->tv_nsec = mts.tv_nsec;
69
    return 0;
70 71 72
}
#endif

73
#ifdef ZMQ_HAVE_WINDOWS
74
typedef ULONGLONG (*f_compatible_get_tick_count64) ();
75 76 77

static zmq::mutex_t compatible_get_tick_count64_mutex;

78
ULONGLONG compatible_get_tick_count64 ()
79
{
80
#ifdef ZMQ_HAVE_WINDOWS_UWP
81 82
    const ULONGLONG result = ::GetTickCount64 ();
    return result;
83
#else
84
    zmq::scoped_lock_t locker (compatible_get_tick_count64_mutex);
85

86 87 88
    static DWORD s_wrap = 0;
    static DWORD s_last_tick = 0;
    const DWORD current_tick = ::GetTickCount ();
89

90 91
    if (current_tick < s_last_tick)
        ++s_wrap;
92

93 94 95
    s_last_tick = current_tick;
    const ULONGLONG result = (static_cast<ULONGLONG> (s_wrap) << 32)
                             + static_cast<ULONGLONG> (current_tick);
96

97
    return result;
98
#endif
99 100
}

101
f_compatible_get_tick_count64 init_compatible_get_tick_count64 ()
102
{
103
    f_compatible_get_tick_count64 func = NULL;
104 105
#if !defined ZMQ_HAVE_WINDOWS_UWP

106 107 108 109
    HMODULE module = ::LoadLibraryA ("Kernel32.dll");
    if (module != NULL)
        func = reinterpret_cast<f_compatible_get_tick_count64> (
          ::GetProcAddress (module, "GetTickCount64"));
110
#endif
111 112
    if (func == NULL)
        func = compatible_get_tick_count64;
113

114
#if !defined ZMQ_HAVE_WINDOWS_UWP
115
    ::FreeLibrary (module);
116
#endif
117

118
    return func;
119 120
}

121 122
static f_compatible_get_tick_count64 my_get_tick_count64 =
  init_compatible_get_tick_count64 ();
123
#endif
124

125 126 127 128
const uint64_t usecs_per_msec = 1000;
const uint64_t usecs_per_sec = 1000000;
const uint64_t nsecs_per_usec = 1000;

Martin Sustrik's avatar
Martin Sustrik committed
129
zmq::clock_t::clock_t () :
130
    _last_tsc (rdtsc ()),
131
#ifdef ZMQ_HAVE_WINDOWS
132
    _last_time (static_cast<uint64_t> ((*my_get_tick_count64) ()))
133
#else
134
    _last_time (now_us () / usecs_per_msec)
135
#endif
Martin Sustrik's avatar
Martin Sustrik committed
136 137 138 139 140 141 142 143
{
}

uint64_t zmq::clock_t::now_us ()
{
#if defined ZMQ_HAVE_WINDOWS

    //  Get the high resolution counter's accuracy.
144 145 146
    //  While QueryPerformanceFrequency only needs to be called once, since its
    //  value does not change during runtime, we query it here since this is a
    //  static function. It might make sense to cache it, though.
147 148
    LARGE_INTEGER ticks_per_second;
    QueryPerformanceFrequency (&ticks_per_second);
Martin Sustrik's avatar
Martin Sustrik committed
149 150 151 152 153 154 155

    //  What time is it?
    LARGE_INTEGER tick;
    QueryPerformanceCounter (&tick);

    //  Convert the tick number into the number of seconds
    //  since the system was started.
156 157
    const double ticks_div =
      static_cast<double> (ticks_per_second.QuadPart) / usecs_per_sec;
158
    return static_cast<uint64_t> (tick.QuadPart / ticks_div);
Martin Sustrik's avatar
Martin Sustrik committed
159

160 161
#elif defined HAVE_CLOCK_GETTIME                                               \
  && (defined CLOCK_MONOTONIC || defined ZMQ_HAVE_VXWORKS)
162 163 164

    //  Use POSIX clock_gettime function to get precise monotonic time.
    struct timespec tv;
165

166 167
#if defined ZMQ_HAVE_OSX                                                       \
  && __MAC_OS_X_VERSION_MIN_REQUIRED < 101200 // less than macOS 10.12
168
    int rc = alt_clock_gettime (SYSTEM_CLOCK, &tv);
169
#else
170
    int rc = clock_gettime (CLOCK_MONOTONIC, &tv);
171
#endif
172 173 174
    // Fix case where system has clock_gettime but CLOCK_MONOTONIC is not supported.
    // This should be a configuration check, but I looked into it and writing an
    // AC_FUNC_CLOCK_MONOTONIC seems beyond my powers.
175
    if (rc != 0) {
176
#ifndef ZMQ_HAVE_VXWORKS
177 178 179 180
        //  Use POSIX gettimeofday function to get precise time.
        struct timeval tv;
        int rc = gettimeofday (&tv, NULL);
        errno_assert (rc == 0);
181
        return tv.tv_sec * usecs_per_sec + tv.tv_usec;
182
#endif
183
    }
184
    return tv.tv_sec * usecs_per_sec + tv.tv_nsec / nsecs_per_usec;
185

186 187
#elif defined HAVE_GETHRTIME

188
    return gethrtime () / nsecs_per_usec;
189

Martin Sustrik's avatar
Martin Sustrik committed
190 191 192 193 194 195
#else

    //  Use POSIX gettimeofday function to get precise time.
    struct timeval tv;
    int rc = gettimeofday (&tv, NULL);
    errno_assert (rc == 0);
196
    return tv.tv_sec * usecs_per_sec + tv.tv_usec;
Martin Sustrik's avatar
Martin Sustrik committed
197 198 199 200 201 202 203 204 205

#endif
}

uint64_t zmq::clock_t::now_ms ()
{
    uint64_t tsc = rdtsc ();

    //  If TSC is not supported, get precise time and chop off the microseconds.
206
    if (!tsc) {
207 208 209 210 211
#ifdef ZMQ_HAVE_WINDOWS
        // Under Windows, now_us is not so reliable since QueryPerformanceCounter
        // does not guarantee that it will use a hardware that offers a monotonic timer.
        // So, lets use GetTickCount when GetTickCount64 is not available with an workaround
        // to its 32 bit limitation.
212
        return static_cast<uint64_t> ((*my_get_tick_count64) ());
213
#else
214
        return now_us () / usecs_per_msec;
215 216
#endif
    }
Martin Sustrik's avatar
Martin Sustrik committed
217 218 219 220

    //  If TSC haven't jumped back (in case of migration to a different
    //  CPU core) and if not too much time elapsed since last measurement,
    //  we can return cached time value.
221 222
    if (likely (tsc - _last_tsc <= (clock_precision / 2) && tsc >= _last_tsc))
        return _last_time;
Martin Sustrik's avatar
Martin Sustrik committed
223

224
    _last_tsc = tsc;
225
#ifdef ZMQ_HAVE_WINDOWS
226
    _last_time = static_cast<uint64_t> ((*my_get_tick_count64) ());
227
#else
228
    _last_time = now_us () / usecs_per_msec;
229
#endif
230
    return _last_time;
Martin Sustrik's avatar
Martin Sustrik committed
231 232 233 234 235
}

uint64_t zmq::clock_t::rdtsc ()
{
#if (defined _MSC_VER && (defined _M_IX86 || defined _M_X64))
Martin Sustrik's avatar
Martin Sustrik committed
236
    return __rdtsc ();
Martin Sustrik's avatar
Martin Sustrik committed
237 238
#elif (defined __GNUC__ && (defined __i386__ || defined __x86_64__))
    uint32_t low, high;
239
    __asm__ volatile("rdtsc" : "=a"(low), "=d"(high));
240
    return static_cast<uint64_t> (high) << 32 | low;
241 242 243 244
#elif (defined __SUNPRO_CC && (__SUNPRO_CC >= 0x5100)                          \
       && (defined __i386 || defined __amd64 || defined __x86_64))
    union
    {
245
        uint64_t u64val;
246
        uint32_t u32val[2];
247
    } tsc;
248
    asm("rdtsc" : "=a"(tsc.u32val[0]), "=d"(tsc.u32val[1]));
249
    return tsc.u64val;
250 251
#elif defined(__s390__)
    uint64_t tsc;
252
    asm("\tstck\t%0\n" : "=Q"(tsc) : : "cc");
253
    return tsc;
Martin Sustrik's avatar
Martin Sustrik committed
254
#else
Laughing's avatar
Laughing committed
255
    struct timespec ts;
256 257 258 259 260 261
#if defined ZMQ_HAVE_OSX                                                       \
  && __MAC_OS_X_VERSION_MIN_REQUIRED < 101200 // less than macOS 10.12
    alt_clock_gettime (SYSTEM_CLOCK, &ts);
#else
    clock_gettime (CLOCK_MONOTONIC, &ts);
#endif
262 263
    return static_cast<uint64_t> (ts.tv_sec) * nsecs_per_usec * usecs_per_sec
           + ts.tv_nsec;
Martin Sustrik's avatar
Martin Sustrik committed
264 265
#endif
}