timeval: Use monotonic time in OVS Python timeval library.
[cascardo/ovs.git] / python / ovs / timeval.py
1 # Copyright (c) 2009, 2010 Nicira, Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at:
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import ctypes
16 import sys
17 import time
18
19 LIBRT = 'librt.so.1'
20 CLOCK_MONOTONIC = 1
21
22 class timespec(ctypes.Structure):
23     _fields_ = [
24         ('tv_sec', ctypes.c_long),
25         ('tv_nsec', ctypes.c_long),
26     ]
27
28 try:
29     librt = ctypes.CDLL(LIBRT)
30     clock_gettime = librt.clock_gettime
31     clock_gettime.argtypes = [ctypes.c_int, ctypes.POINTER(timespec)]
32 except:
33     # Librt shared library could not be loaded
34     librt = None
35
36 def monotonic():
37     if not librt:
38         return time.time()
39
40     t = timespec()
41     if clock_gettime(CLOCK_MONOTONIC, ctypes.pointer(t)) == 0:
42         return t.tv_sec + t.tv_nsec * 1e-9
43     # Kernel does not support CLOCK_MONOTONIC
44     return time.time()
45
46 # Use time.monotonic() if Python version >= 3.3
47 if not hasattr(time, 'monotonic'):
48     time.monotonic = monotonic
49
50 def msec():
51     """Returns the current time, as the amount of time since the epoch, in
52     milliseconds, as a float."""
53     return time.monotonic() * 1000.0
54
55
56 def postfork():
57     # Just a stub for now
58     pass