Python time.time_ns() Examples

The following are 26 code examples of time.time_ns(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module time , or try the search function .
Example #1
Source File: frame.py    From PyPCAPKit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #2
Source File: ordercontroller.py    From ewm-cloud-robotics with Apache License 2.0 6 votes vote down vote up
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) 
Example #3
Source File: test_time.py    From android_universal with MIT License 6 votes vote down vote up
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)) 
Example #4
Source File: info.py    From android-catcher with MIT License 6 votes vote down vote up
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) 
Example #5
Source File: common.py    From synapse with Apache License 2.0 6 votes vote down vote up
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 
Example #6
Source File: timing.py    From angr with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 
Example #7
Source File: node.py    From pyuavcan with MIT License 6 votes vote down vote up
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) 
Example #8
Source File: engine_extension.py    From graphene-tornado with MIT License 5 votes vote down vote up
def now_ns() -> int:
    return time.time_ns() 
Example #9
Source File: common.py    From certidude with MIT License 5 votes vote down vote up
def generate_serial():
    return time_ns() << 56 | random.randint(0, 2**56-1) 
Example #10
Source File: async_producer_consumer.py    From w1thermsensor with MIT License 5 votes vote down vote up
def produce_readings(sensor: AsyncW1ThermSensor, queue: asyncio.Queue):
    """Single async producer which reads a temperature from a single sensor"""
    while True:
        timestamp = time.time_ns() / 1e9
        temperature = await sensor.get_temperature()
        await queue.put(Reading(sensor.id, timestamp, temperature)) 
Example #11
Source File: async_producer_threading_consumer.py    From w1thermsensor with MIT License 5 votes vote down vote up
def produce_readings(sensor: AsyncW1ThermSensor, queue: asyncio.Queue):
    """Single async producer which reads a temperature from a single sensor"""
    while True:
        timestamp = time.time_ns() / 1e9
        temperature = await sensor.get_temperature()
        await queue.put(Reading(sensor.id, timestamp, temperature)) 
Example #12
Source File: utils.py    From pyquarkchain with MIT License 5 votes vote down vote up
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) 
Example #13
Source File: time_funcs.py    From ttp with MIT License 5 votes vote down vote up
def get_time_ns(*args, **kwargs):
    # Return the current time in nanoseconds since the Epoch
    return time.time_ns() 
Example #14
Source File: _timestamp.py    From pyuavcan with MIT License 5 votes vote down vote up
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}') 
Example #15
Source File: DataItem.py    From nionswift with GNU General Public License v3.0 5 votes vote down vote up
def utcnow(cls) -> datetime.datetime:
        # windows utcnow has a resolution of 1ms, this sleep can guarantee unique times for all created times during a particular test.
        if sys.platform == "win32":
            # see https://www.python.org/dev/peps/pep-0564/#annex-clocks-resolution-in-python
            if sys.version_info.major == 3 and sys.version_info.minor >= 7:
                utcnow = datetime.datetime.utcfromtimestamp(time.time_ns() / 1E9)
                time.sleep(0.0004)
            else:
                utcnow = datetime.datetime.utcfromtimestamp(time.time())
                print(utcnow, datetime.datetime.utcnow())
                time.sleep(0.0009)
        else:
            utcnow = datetime.datetime.utcnow()
        return utcnow 
Example #16
Source File: benchmark_utils.py    From py-mongosql with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def start(self, name):
        """ Start measuring time for `name` """
        self._timers[name] = time_ns() 
Example #17
Source File: canary.py    From aws-embedded-metrics-python with Apache License 2.0 5 votes vote down vote up
def main():
    init = True
    duration = None
    # wait for agent to start
    # TODO: this should not be needed if we're using a ring buffer to queue and re-try events
    await asyncio.sleep(10)
    while True:
        # capture the approximate run time of the method
        last_run_at = time.time_ns()
        await app(init, duration)
        duration = time.time_ns() - last_run_at
        await asyncio.sleep(0.2)
        init = False 
Example #18
Source File: testutils.py    From sygnal with Apache License 2.0 5 votes vote down vote up
def config_setup(self, config):
        self.dbname = "_sygnal_%s" % (time_ns())
        if USE_POSTGRES:
            config["database"] = {
                "name": "psycopg2",
                "args": {
                    "user": POSTGRES_USER,
                    "password": POSTGRES_PASSWORD,
                    "database": self.dbname,
                    "host": POSTGRES_HOST,
                },
            }
        else:
            config["database"] = {"name": "sqlite3", "args": {"dbfile": ":memory:"}} 
Example #19
Source File: common.py    From certidude with MIT License 5 votes vote down vote up
def time_ns():
        return int(time() * 10**9) # 64 bits integer, 32 ns bits 
Example #20
Source File: __init__.py    From opentelemetry-python with Apache License 2.0 5 votes vote down vote up
def time_ns() -> int:
        return int(time.time() * 1e9) 
Example #21
Source File: _util.py    From txaio with MIT License 5 votes vote down vote up
def time_ns():
        """
        Shim for standard library time.time_ns for Python < 3.7.
        """
        return int(time.time() * 1000000000.) 
Example #22
Source File: multicore.py    From imgaug with MIT License 5 votes vote down vote up
def _Pool_initialize_worker(augseq, seed_start):
    # pylint: disable=invalid-name, protected-access

    # Not using this seems to have caused infinite hanging in the case
    # of gaussian blur on at least MacOSX.
    # It is also in most cases probably not sensible to use multiple
    # threads while already running augmentation in multiple processes.
    cv2.setNumThreads(0)

    if seed_start is None:
        # pylint falsely thinks in older versions that
        # multiprocessing.current_process() was not callable, see
        # https://github.com/PyCQA/pylint/issues/1699
        # pylint: disable=not-callable
        process_name = _get_context().current_process().name
        # pylint: enable=not-callable

        # time_ns() exists only in 3.7+
        if sys.version_info[0] == 3 and sys.version_info[1] >= 7:
            seed_offset = time.time_ns()
        else:
            seed_offset = int(time.time() * 10**6) % 10**6
        seed = hash(process_name) + seed_offset
        _reseed_global_local(seed, augseq)
    Pool._WORKER_SEED_START = seed_start
    Pool._WORKER_AUGSEQ = augseq
    # not sure if really necessary, but shouldn't hurt either
    Pool._WORKER_AUGSEQ.localize_random_state_()


# This could be a classmethod or staticmethod of Pool in 3.x, but in 2.7 that
# leads to pickle errors. 
Example #23
Source File: _timestamp.py    From pyuavcan with MIT License 5 votes vote down vote up
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()) 
Example #24
Source File: benchmark_utils.py    From py-mongosql with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 
Example #25
Source File: benchmark_utils.py    From py-mongosql with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 
Example #26
Source File: info.py    From android-catcher with MIT License 4 votes vote down vote up
def get_net_info(self):
        command = "cat /proc/" + self.task.pid + "/net/dev | grep wlan"
        dirs = self.task.output + "/net_stats/"
        file_name = "net_" + self.task.device + "_" + self.task.applicationid + "_" + self.task.version_name + "_" + self.task.name
        field_names = [self.TIME,
                       self.DOWN_SPEED,
                       self.UP_SPEED,
                       self.AVERAGE_DOWN_SPEED,
                       self.AVERAGEUP_SPEED,
                       self.TOTAL_DOWN_SPEED,
                       self.TOTAL_UP_SPEED]
        writer = utils.get_csv_writer(dirs, file_name, field_names)
        while self.is_running:
            if self.is_first:
                self.start_time = time.time_ns()
                self.last_time = self.start_time
                net_info = self.task.d.adb_shell(command)
                net_array = re.split("\s+", net_info)
                self.start_net_down = int(net_array[2])
                self.last_net_down = self.start_net_down
                self.start_net_up = int(net_array[10])
                self.last_net_up = self.start_net_up
                self.is_first = False
            current_time = time.time_ns()
            current_info = self.task.d.adb_shell(command)
            current_array = re.split("\s+", current_info)
            current_net_down = int(current_array[2])
            current_net_up = int(current_array[10])
            time_delta = (current_time - self.last_time) / 1000000000.0
            time_total = (current_time - self.start_time) / 1000000000.0
            net_delta_up = (current_net_up - self.last_net_up) / 1024.0
            net_delta_down = (current_net_down - self.last_net_down) / 1024.0
            net_total_up = (current_net_up - self.start_net_up) / 1024.0
            net_total_down = (current_net_down - self.start_net_down) / 1024.0
            net_speed_up = net_delta_up / time_delta
            net_speed_down = net_delta_down / time_delta
            net_average_speed_up = net_total_up / time_total
            net_average_speed_down = net_total_down / time_total

            writer.writerow({self.TIME: self.get_index(),
                             self.DOWN_SPEED: "{:.2f}".format(net_speed_down),
                             self.UP_SPEED: "{:.2f}".format(net_speed_up),
                             self.AVERAGE_DOWN_SPEED: "{:.2f}".format(net_average_speed_down),
                             self.AVERAGEUP_SPEED: "{:.2f}".format(net_average_speed_up),
                             self.TOTAL_DOWN_SPEED: "{:.2f}".format(net_total_down),
                             self.TOTAL_UP_SPEED: "{:.2f}".format(net_total_up)
                             })
            # print("下载速度:{:.2f} KB/s".format(net_speed_down))
            # print("上传速度:{:.2f} KB/s".format(net_speed_up))
            # print("平均下载速度:{:.2f} KB/s".format(net_average_speed_down))
            # print("平均上传速度:{:.2f} KB/s".format(net_average_speed_up))
            # print("下载总流量:{:.0f} KB/s".format(net_total_down))
            # print("上传总流量:{:.0f} KB/s".format(net_total_up))
            # print("\n")
            self.last_time = current_time
            self.last_net_up = current_net_up
            self.last_net_down = current_net_down
            self.count += 1
            time.sleep(self.task.interval)