本文整理汇总了Python中time.time_ns方法的典型用法代码示例。如果您正苦于以下问题:Python time.time_ns方法的具体用法?Python time.time_ns怎么用?Python time.time_ns使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类time
的用法示例。
在下文中一共展示了time.time_ns方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _register_output_transfer_id_map_save_at_exit
# 需要导入模块: import time [as 别名]
# 或者: from time import time_ns [as 别名]
def _register_output_transfer_id_map_save_at_exit(presentation: pyuavcan.presentation.Presentation) -> None:
# We MUST sample the configuration early because if this is a redundant transport it may reset its
# reported descriptor and local node-ID back to default after close().
local_node_id = presentation.transport.local_node_id
descriptor = presentation.transport.descriptor
def do_save_at_exit() -> None:
if local_node_id is not None:
file_path = _get_output_transfer_id_file_path(local_node_id, descriptor)
tmp_path = f'{file_path}.{os.getpid()}.{time.time_ns()}.tmp'
_logger.debug('Output TID map save: %s --> %s', tmp_path, file_path)
with open(tmp_path, 'wb') as f:
pickle.dump(presentation.output_transfer_id_map, f)
# We use replace for compatibility reasons. On POSIX, a call to rename() will be made, which is
# guaranteed to be atomic. On Windows this may fall back to non-atomic copy, which is still
# acceptable for us here. If the file ends up being damaged, we'll simply ignore it at next startup.
os.replace(tmp_path, file_path)
try:
os.unlink(tmp_path)
except OSError:
pass
else:
_logger.debug('Output TID map NOT saved because the transport instance is anonymous')
atexit.register(do_save_at_exit)
示例2: timethis
# 需要导入模块: import time [as 别名]
# 或者: from time import time_ns [as 别名]
def timethis(func):
@wraps(func)
def timed_func(*args, **kwargs):
if TIMING:
if sys.version_info >= (3,7):
_t = lambda: time.time_ns() / 1000000
else:
_t = lambda: time.time() * 1000
start = _t()
r = func(*args, **kwargs)
millisec = _t() - start
sec = millisec / 1000
if sec > 1.0:
print("[timing] %s took %f seconds (%f milliseconds)." % (func.__name__, sec, millisec))
else:
print("[timing] %s took %f milliseconds." % (func.__name__, millisec))
return r
else:
return func(*args, **kwargs)
return timed_func
示例3: _make_timestamp
# 需要导入模块: import time [as 别名]
# 或者: from time import time_ns [as 别名]
def _make_timestamp(self, **kwargs): # pylint: disable=no-self-use
"""Make timestamp.
Keyword Args:
**kwargs: Arbitrary keyword arguments.
Returns:
Tuple[int, int]: Second and microsecond/nanosecond value of timestamp.
"""
nanosecond = kwargs.get('nanosecond', False) # nanosecond-resolution file flag
timestamp = kwargs.get('timestamp', time.time()) # timestamp
ts_sec = kwargs.get('ts_sec', int(timestamp)) # timestamp seconds
if py37 and nanosecond:
_default_ts_usec = time.time_ns() % 1000000000
else:
_default_ts_usec = int((timestamp - ts_sec) * (1000000000 if nanosecond else 1000000))
ts_usec = kwargs.get('ts_usec', _default_ts_usec) # timestamp microseconds
return ts_sec, ts_usec
示例4: now
# 需要导入模块: import time [as 别名]
# 或者: from time import time_ns [as 别名]
def now():
'''
Get the current epoch time in milliseconds.
This relies on time.time(), which is system-dependent in terms of resolution.
Examples:
Get the current time and make a row for a Cortex::
tick = now()
row = (someiden, 'foo:prop', 1, tick)
core.addRows([row])
Returns:
int: Epoch time in milliseconds.
'''
return time.time_ns() // 1000000
示例5: get_fps_info
# 需要导入模块: import time [as 别名]
# 或者: from time import time_ns [as 别名]
def get_fps_info(self):
command = "dumpsys gfxinfo " + self.task.pid + " | grep 'Total frames'"
dirs = self.task.output + "/fps_stats/"
file_name = "fps_" + self.task.device + "_" + self.task.applicationid + "_" + self.task.version_name + "_" + self.task.name
field_names = [self.TIME, self.FPS]
writer = utils.get_csv_writer(dirs, file_name, field_names)
while self.is_running:
if self.is_first:
self.last_time = time.time_ns()
self.last_fps = int(re.findall("\d+", self.task.d.adb_shell(command))[0])
self.is_first = False
current_time = time.time_ns()
current_fps = int(re.findall("\d+", self.task.d.adb_shell(command))[0])
time_delta = (current_time - self.last_time) / 1000000000.0
fps_delta = current_fps - self.last_fps
fps = fps_delta / time_delta
self.last_time = current_time
self.last_fps = current_fps
writer.writerow({self.TIME: self.get_index(), self.FPS: "{:.2f}".format(fps)})
self.count += 1
time.sleep(self.task.interval)
示例6: test_time_ns_type
# 需要导入模块: import time [as 别名]
# 或者: from time import time_ns [as 别名]
def test_time_ns_type(self):
def check_ns(sec, ns):
self.assertIsInstance(ns, int)
sec_ns = int(sec * 1e9)
# tolerate a difference of 50 ms
self.assertLess((sec_ns - ns), 50 ** 6, (sec, ns))
check_ns(time.time(),
time.time_ns())
check_ns(time.monotonic(),
time.monotonic_ns())
check_ns(time.perf_counter(),
time.perf_counter_ns())
check_ns(time.process_time(),
time.process_time_ns())
if hasattr(time, 'thread_time'):
check_ns(time.thread_time(),
time.thread_time_ns())
if hasattr(time, 'clock_gettime'):
check_ns(time.clock_gettime(time.CLOCK_REALTIME),
time.clock_gettime_ns(time.CLOCK_REALTIME))
示例7: send_who_to_robot
# 需要导入模块: import time [as 别名]
# 或者: from time import time_ns [as 别名]
def send_who_to_robot(self, robotident: RobotIdentifier, who: Dict) -> None:
"""Send the warehouse order to a robot."""
labels = {}
# Robot name and warehouse order CR names must be lower case
labels['cloudrobotics.com/robot-name'] = robotident.rsrc.lower()
name = '{lgnum}.{who}'.format(lgnum=who['lgnum'], who=who['who']).lower()
# Warehouse order are procssed by the robot in the sequence they are assigned to them
spec = {
'data': who,
'order_status': WarehouseOrderCRDSpec.STATE_RUNNING,
'sequence': time.time_ns()}
if self.check_cr_exists(name):
_LOGGER.debug('Warehouse order CR "%s" exists. Update it', name)
cr_old = self.get_cr(name)
robot_old = cr_old['metadata'].get('labels', {}).get('cloudrobotics.com/robot-name')
order_status_old = cr_old['spec'].get('order_status')
# Keep the sequence if it is set and order_status or robot-name label did not change
if robot_old == robotident.rsrc.lower() and order_status_old == spec['order_status']:
spec['sequence'] = cr_old['spec'].get('sequence', 0)
# Update CR
self.update_cr_spec(name, spec, labels)
else:
_LOGGER.debug('Warehouse order CR "%s" not existing. Create it', name)
spec['sequence'] = time.time_ns()
self.create_cr(name, labels, spec)
示例8: time_ns
# 需要导入模块: import time [as 别名]
# 或者: from time import time_ns [as 别名]
def time_ns():
return int(time() * 10**9) # 64 bits integer, 32 ns bits
示例9: generate_serial
# 需要导入模块: import time [as 别名]
# 或者: from time import time_ns [as 别名]
def generate_serial():
return time_ns() << 56 | random.randint(0, 2**56-1)
示例10: time_ms
# 需要导入模块: import time [as 别名]
# 或者: from time import time_ns [as 别名]
def time_ms():
"""currently pypy only has Python 3.5.3, so we are missing Python 3.7's time.time_ns() with better precision
see https://www.python.org/dev/peps/pep-0564/
the function here is a convenience; you shall use `time.time_ns() // 1e6` if using >=Python 3.7
"""
return int(time.time() * 1e3)
示例11: __init__
# 需要导入模块: import time [as 别名]
# 或者: from time import time_ns [as 别名]
def __init__(self, system_ns: int, monotonic_ns: int) -> None:
"""
Manual construction is rarely needed, except when implementing network drivers.
See the static factory methods.
:param system_ns: Belongs to the domain of :func:`time.time_ns`. Units are nanoseconds.
:param monotonic_ns: Belongs to the domain of :func:`time.monotonic_ns`. Units are nanoseconds.
"""
self._system_ns = int(system_ns)
self._monotonic_ns = int(monotonic_ns)
if self._system_ns < 0 or self._monotonic_ns < 0:
raise ValueError(f'Neither of the timestamp samples can be negative; found this: {self!r}')
示例12: now
# 需要导入模块: import time [as 别名]
# 或者: from time import time_ns [as 别名]
def now() -> Timestamp:
"""
Constructs a new timestamp instance populated with current time.
.. important:: Clocks are sampled non-atomically! Monotonic sampled first.
"""
return Timestamp(monotonic_ns=time.monotonic_ns(), system_ns=time.time_ns())
示例13: start
# 需要导入模块: import time [as 别名]
# 或者: from time import time_ns [as 别名]
def start(self, name):
""" Start measuring time for `name` """
self._timers[name] = time_ns()
示例14: stop
# 需要导入模块: import time [as 别名]
# 或者: from time import time_ns [as 别名]
def stop(self, name):
""" Stop measuring time for `name`.
You can add more time by calling start()/stop() again.
"""
total = time_ns() - self._timers[name]
self._results[name] += total
示例15: benchmark_parallel
# 需要导入模块: import time [as 别名]
# 或者: from time import time_ns [as 别名]
def benchmark_parallel(n_iterations, n_parts, **tests):
""" Run the given tests in parallel.
It will switch between all the given tests back and forth, making sure that some local
performance fluctuations won't hurt running the tests.
Args
----
n_iterations: int
The total number of iterations
n_parts: int
The number of parts to break those iterations into
tests:
Named tests to run.
Each is a callable that receives the `n` argument: number of repetitions
"""
timers = Nanotimers()
iters_per_run = n_iterations // n_parts
# Run
for run in range(n_parts):
for name, test in tests.items():
timers.start(name)
test(iters_per_run)
timers.stop(name)
# Fix overhead
# Measure overhead: call an empty function the same number of times
def f(): pass
t1 = time_ns()
for i in range(n_iterations): f()
t2 = time_ns()
overhead_ns = t2 - t1
# Fix it: shift all results by the measured number of nanoseconds
timers.overhead_shift(overhead_ns)
# Done
return timers