Python time.monotonic() Examples

The following are 30 code examples for showing how to use time.monotonic(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module time , or try the search function .

Example 1
Project: botbuilder-python   Author: microsoft   File: dialog_test_logger.py    License: MIT License 6 votes vote down vote up
def __init__(
        self,
        log_func: Callable[..., None] = None,
        json_indent: int = 4,
        time_func: Callable[[], float] = None,
    ):
        """
        Initialize a new instance of the dialog test logger.

        :param log_func: A callable method or object that can log a message,
        default to `logging.getLogger(__name__).info`.
        :type log_func: Callable[..., None]
        :param json_indent: An indent for json output, default indent is 4.
        :type json_indent: int
        :param time_func: A time function to record time spans, default to `time.monotonic`.
        :type time_func: Callable[[], float]
        """
        self._log = logging.getLogger(__name__).info if log_func is None else log_func
        self._stopwatch_state_key = f"stopwatch.{uuid.uuid4()}"
        self._json_indent = json_indent
        self._time_func = time.monotonic if time_func is None else time_func 
Example 2
Project: jawfish   Author: war-and-code   File: threading.py    License: MIT License 6 votes vote down vote up
def wait_for(self, predicate, timeout=None):
        """Wait until a condition evaluates to True.

        predicate should be a callable which result will be interpreted as a
        boolean value.  A timeout may be provided giving the maximum time to
        wait.

        """
        endtime = None
        waittime = timeout
        result = predicate()
        while not result:
            if waittime is not None:
                if endtime is None:
                    endtime = _time() + waittime
                else:
                    waittime = endtime - _time()
                    if waittime <= 0:
                        break
            self.wait(waittime)
            result = predicate()
        return result 
Example 3
Project: gist-alfred   Author: danielecook   File: wait.py    License: MIT License 6 votes vote down vote up
def _retry_on_intr(fn, timeout):
        if timeout is None:
            deadline = float("inf")
        else:
            deadline = monotonic() + timeout

        while True:
            try:
                return fn(timeout)
            # OSError for 3 <= pyver < 3.5, select.error for pyver <= 2.7
            except (OSError, select.error) as e:
                # 'e.args[0]' incantation works for both OSError and select.error
                if e.args[0] != errno.EINTR:
                    raise
                else:
                    timeout = deadline - monotonic()
                    if timeout < 0:
                        timeout = 0
                    if timeout == float("inf"):
                        timeout = None
                    continue 
Example 4
Project: misp42splunk   Author: remg427   File: wait.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def _retry_on_intr(fn, timeout):
        if timeout is None:
            deadline = float("inf")
        else:
            deadline = monotonic() + timeout

        while True:
            try:
                return fn(timeout)
            # OSError for 3 <= pyver < 3.5, select.error for pyver <= 2.7
            except (OSError, select.error) as e:
                # 'e.args[0]' incantation works for both OSError and select.error
                if e.args[0] != errno.EINTR:
                    raise
                else:
                    timeout = deadline - monotonic()
                    if timeout < 0:
                        timeout = 0
                    if timeout == float("inf"):
                        timeout = None
                    continue 
Example 5
Project: misp42splunk   Author: remg427   File: wait.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def _retry_on_intr(fn, timeout):
        if timeout is None:
            deadline = float("inf")
        else:
            deadline = monotonic() + timeout

        while True:
            try:
                return fn(timeout)
            # OSError for 3 <= pyver < 3.5, select.error for pyver <= 2.7
            except (OSError, select.error) as e:
                # 'e.args[0]' incantation works for both OSError and select.error
                if e.args[0] != errno.EINTR:
                    raise
                else:
                    timeout = deadline - monotonic()
                    if timeout < 0:
                        timeout = 0
                    if timeout == float("inf"):
                        timeout = None
                    continue 
Example 6
Project: qutebrowser   Author: qutebrowser   File: throttle.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __call__(self, *args: typing.Any, **kwargs: typing.Any) -> typing.Any:
        cur_time_ms = int(time.monotonic() * 1000)
        if self._pending_call is None:
            if (self._last_call_ms is None or
                    cur_time_ms - self._last_call_ms > self._delay_ms):
                # Call right now
                self._last_call_ms = cur_time_ms
                self._func(*args, **kwargs)
                return

            self._timer.setInterval(self._delay_ms -
                                    (cur_time_ms - self._last_call_ms))
            # Disconnect any existing calls, continue if no connections.
            try:
                self._timer.timeout.disconnect()
            except TypeError:
                pass
            self._timer.timeout.connect(self._call_pending)
            self._timer.start()

        # Update arguments for an existing pending call
        self._pending_call = _CallArgs(args=args, kwargs=kwargs) 
Example 7
Project: recruit   Author: Frank-qlu   File: thread_util.py    License: Apache License 2.0 6 votes vote down vote up
def acquire(self, blocking=True, timeout=None):
        if not blocking and timeout is not None:
            raise ValueError("can't specify timeout for non-blocking acquire")
        rc = False
        endtime = None
        self._cond.acquire()
        while self._value == 0:
            if not blocking:
                break
            if timeout is not None:
                if endtime is None:
                    endtime = _time() + timeout
                else:
                    timeout = endtime - _time()
                    if timeout <= 0:
                        break
            self._cond.wait(timeout)
        else:
            self._value = self._value - 1
            rc = True
        self._cond.release()
        return rc 
Example 8
Project: schemathesis   Author: kiwicom   File: core.py    License: MIT License 6 votes vote down vote up
def execute(self) -> Generator[events.ExecutionEvent, None, None]:
        """Common logic for all runners."""
        results = TestResultSet()

        initialized = events.Initialized.from_schema(schema=self.schema)
        yield initialized

        for event in self._execute(results):
            if (
                self.exit_first
                and isinstance(event, events.AfterExecution)
                and event.status in (Status.error, Status.failure)
            ):
                break
            yield event

        yield events.Finished.from_results(results=results, running_time=time.monotonic() - initialized.start_time) 
Example 9
Project: schemathesis   Author: kiwicom   File: core.py    License: MIT License 6 votes vote down vote up
def _wsgi_test(
    case: Case,
    checks: Iterable[CheckFunction],
    targets: Iterable[Target],
    result: TestResult,
    headers: Dict[str, Any],
    store_interactions: bool,
    feedback: Feedback,
) -> WSGIResponse:
    # pylint: disable=too-many-arguments
    with catching_logs(LogCaptureHandler(), level=logging.DEBUG) as recorded:
        start = time.monotonic()
        response = case.call_wsgi(headers=headers)
        elapsed = time.monotonic() - start
    run_targets(targets, elapsed)
    if store_interactions:
        result.store_wsgi_response(case, response, headers, elapsed)
    result.logs.extend(recorded.records)
    run_checks(case, checks, result, response)
    feedback.add_test_case(case, response)
    return response 
Example 10
Project: discord.py   Author: Rapptz   File: backoff.py    License: MIT License 6 votes vote down vote up
def delay(self):
        """Compute the next delay

        Returns the next delay to wait according to the exponential
        backoff algorithm.  This is a value between 0 and base * 2^exp
        where exponent starts off at 1 and is incremented at every
        invocation of this method up to a maximum of 10.

        If a period of more than base * 2^11 has passed since the last
        retry, the exponent is reset to 1.
        """
        invocation = time.monotonic()
        interval = invocation - self._last_invocation
        self._last_invocation = invocation

        if interval > self._reset_time:
            self._exp = 0

        self._exp = min(self._exp + 1, self._max)
        return self._randfunc(0, self._base * 2 ** self._exp) 
Example 11
Project: pyquarkchain   Author: QuarkChain   File: kademlia.py    License: MIT License 6 votes vote down vote up
def add(self, node: Node) -> Node:
        """Try to add the given node to this bucket.

        If the node is already present, it is moved to the tail of the list, and we return None.

        If the node is not already present and the bucket has fewer than k entries, it is inserted
        at the tail of the list, and we return None.

        If the bucket is full, we add the node to the bucket's replacement cache and return the
        node at the head of the list (i.e. the least recently seen), which should be evicted if it
        fails to respond to a ping.
        """
        self.last_updated = time.monotonic()
        if node in self.nodes:
            self.nodes.remove(node)
            self.nodes.append(node)
        elif len(self) < self.k:
            self.nodes.append(node)
        else:
            self.replacement_cache.append(node)
            return self.head
        return None 
Example 12
Project: pyuavcan   Author: UAVCAN   File: heartbeat_publisher.py    License: MIT License 6 votes vote down vote up
def _task_function(self) -> None:
        next_heartbeat_at = time.monotonic()
        while self._maybe_task:
            try:
                self._call_pre_heartbeat_handlers()
                if self._presentation.transport.local_node_id is not None:
                    if not await self._publisher.publish(self.make_message()):
                        _logger.warning('%s heartbeat send timed out', self)

                next_heartbeat_at += self._publisher.send_timeout
                await asyncio.sleep(next_heartbeat_at - time.monotonic())
            except asyncio.CancelledError:
                _logger.debug('%s publisher task cancelled', self)
                break
            except pyuavcan.transport.ResourceClosedError as ex:
                _logger.debug('%s transport closed, publisher task will exit: %s', self, ex)
                break
            except Exception as ex:
                _logger.exception('%s publisher task exception: %s', self, ex)
        try:
            self._publisher.close()
        except pyuavcan.transport.TransportError:
            pass 
Example 13
Project: torf   Author: rndusr   File: _generate.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __call__(self, cb_args, force_call=False):
        now = time_monotonic()
        prev_call_time = self._prev_call_time
        # _debug(f'CancelCallback: force_call={force_call}, prev_call_time={prev_call_time}, '
        #        f'now={now}, self._interval={self._interval}: {cb_args[1:]}')
        if (force_call or                             # Special case (e.g. exception in Torrent.verify())
            prev_call_time is None or                 # This is the first call
            now - prev_call_time >= self._interval):  # Previous call was at least `interval` seconds ago
            self._prev_call_time = now
            try:
                _debug(f'CancelCallback: Calling callback with {cb_args[1:]}')
                return_value = self._callback(*cb_args)
                if return_value is not None:
                    _debug(f'CancelCallback: Callback cancelled: {return_value!r}')
                    self._cancelled()
                    return True
                return False
            except BaseException as e:
                _debug(f'CancelCallback: Caught exception: {e!r}')
                self._cancelled()
                raise 
Example 14
Project: rlgraph   Author: rlgraph   File: test_apex_agent_long_task_learning.py    License: Apache License 2.0 6 votes vote down vote up
def test_worker_init(self):
        """
        Tests if workers initialize without problems for the pong config.
        """
        agent_config = config_from_path("configs/ray_apex_for_pong.json")

        # Long initialization times can lead to Ray crashes.
        start = time.monotonic()
        executor = ApexExecutor(
            environment_spec=self.env_spec,
            agent_config=agent_config,
        )
        end = time.monotonic() - start
        print("Initialized {} workers in {} s.".format(
            executor.num_sample_workers, end
        ))
        executor.test_worker_init() 
Example 15
Project: mmdetection   Author: open-mmlab   File: profiling.py    License: Apache License 2.0 5 votes vote down vote up
def profile_time(trace_name,
                     name,
                     enabled=True,
                     stream=None,
                     end_stream=None):
        """Print time spent by CPU and GPU.

        Useful as a temporary context manager to find sweet spots of code
        suitable for async implementation.
        """
        if (not enabled) or not torch.cuda.is_available():
            yield
            return
        stream = stream if stream else torch.cuda.current_stream()
        end_stream = end_stream if end_stream else stream
        start = torch.cuda.Event(enable_timing=True)
        end = torch.cuda.Event(enable_timing=True)
        stream.record_event(start)
        try:
            cpu_start = time.monotonic()
            yield
        finally:
            cpu_end = time.monotonic()
            end_stream.record_event(end)
            end.synchronize()
            cpu_time = (cpu_end - cpu_start) * 1000
            gpu_time = start.elapsed_time(end)
            msg = f'{trace_name} {name} cpu_time {cpu_time:.2f} ms '
            msg += f'gpu_time {gpu_time:.2f} ms stream {stream}'
            print(msg, end_stream) 
Example 16
Project: jawfish   Author: war-and-code   File: subprocess.py    License: MIT License 5 votes vote down vote up
def _remaining_time(self, endtime):
        """Convenience for _communicate when computing timeouts."""
        if endtime is None:
            return None
        else:
            return endtime - _time() 
Example 17
Project: jawfish   Author: war-and-code   File: subprocess.py    License: MIT License 5 votes vote down vote up
def _check_timeout(self, endtime, orig_timeout):
        """Convenience for checking if a timeout has expired."""
        if endtime is None:
            return
        if _time() > endtime:
            raise TimeoutExpired(self.args, orig_timeout) 
Example 18
Project: jawfish   Author: war-and-code   File: subprocess.py    License: MIT License 5 votes vote down vote up
def wait(self, timeout=None, endtime=None):
            """Wait for child process to terminate.  Returns returncode
            attribute."""
            if self.returncode is not None:
                return self.returncode

            # endtime is preferred to timeout.  timeout is only used for
            # printing.
            if endtime is not None or timeout is not None:
                if endtime is None:
                    endtime = _time() + timeout
                elif timeout is None:
                    timeout = self._remaining_time(endtime)

            if endtime is not None:
                # Enter a busy loop if we have a timeout.  This busy loop was
                # cribbed from Lib/threading.py in Thread.wait() at r71065.
                delay = 0.0005 # 500 us -> initial delay of 1 ms
                while True:
                    (pid, sts) = self._try_wait(os.WNOHANG)
                    assert pid == self.pid or pid == 0
                    if pid == self.pid:
                        self._handle_exitstatus(sts)
                        break
                    remaining = self._remaining_time(endtime)
                    if remaining <= 0:
                        raise TimeoutExpired(self.args, timeout)
                    delay = min(delay * 2, remaining, .05)
                    time.sleep(delay)
            else:
                while self.returncode is None:
                    (pid, sts) = self._try_wait(0)
                    # Check the pid and loop as waitpid has been known to return
                    # 0 even without WNOHANG in odd situations.  issue14396.
                    if pid == self.pid:
                        self._handle_exitstatus(sts)
            return self.returncode 
Example 19
Project: jawfish   Author: war-and-code   File: queue.py    License: MIT License 5 votes vote down vote up
def put(self, item, block=True, timeout=None):
        '''Put an item into the queue.

        If optional args 'block' is true and 'timeout' is None (the default),
        block if necessary until a free slot is available. If 'timeout' is
        a non-negative number, it blocks at most 'timeout' seconds and raises
        the Full exception if no free slot was available within that time.
        Otherwise ('block' is false), put an item on the queue if a free slot
        is immediately available, else raise the Full exception ('timeout'
        is ignored in that case).
        '''
        with self.not_full:
            if self.maxsize > 0:
                if not block:
                    if self._qsize() >= self.maxsize:
                        raise Full
                elif timeout is None:
                    while self._qsize() >= self.maxsize:
                        self.not_full.wait()
                elif timeout < 0:
                    raise ValueError("'timeout' must be a non-negative number")
                else:
                    endtime = time() + timeout
                    while self._qsize() >= self.maxsize:
                        remaining = endtime - time()
                        if remaining <= 0.0:
                            raise Full
                        self.not_full.wait(remaining)
            self._put(item)
            self.unfinished_tasks += 1
            self.not_empty.notify() 
Example 20
Project: rift-python   Author: brunorijsman   File: interface_stats.py    License: Apache License 2.0 5 votes vote down vote up
def measure_if_stats(ns_name):
    try:
        result = subprocess.run(['ip', 'netns', 'exec', ns_name, 'ifconfig'],
                                stdout=subprocess.PIPE)
    except FileNotFoundError:
        fatal_error('"ifconfig" command not found')
    output = result.stdout.decode('ascii')
    counters = {}
    lines = output.splitlines()
    while True:
        if not lines:
            return (time.monotonic(), counters)
        line = lines.pop(0)
        if "Link encap" not in line:
            continue
        if_name = line.split()[0]
        while True:
            if not lines:
                fatal_error("Missing RX or TX stats in output of ifconfig")
            line = lines.pop(0)
            if "RX packets" in line:
                rx_packets = int(line.split()[1].split(":")[1])
            if "TX packets" in line:
                tx_packets = int(line.split()[1].split(":")[1])
                counters[if_name] = (rx_packets, tx_packets)
                break 
Example 21
Project: rift-python   Author: brunorijsman   File: fsm.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, fsm, from_state, event, verbose, queue_time):
        self.fsm = fsm
        self.seq_nr = FsmRecord._next_seq_nr
        FsmRecord._next_seq_nr += 1
        self.time = time.monotonic()
        self.queue_time = queue_time
        self.processing_time = None
        self.skipped = 0
        self.from_state = from_state
        self.event = event
        self.verbose = verbose
        self.actions_and_pushed_events = []
        self.to_state = None
        self.implicit = False 
Example 22
Project: rift-python   Author: brunorijsman   File: fsm.py    License: Apache License 2.0 5 votes vote down vote up
def start(self):
        self._state = self._definition.initial_state
        self.info("Start FSM, state=%s", self._state.name)
        # Record start state and start state entry actions as from-state=None, and event=None
        self._current_record = FsmRecord(self, None, None, False, 0.0)
        start_time = time.monotonic()
        self._current_record.to_state = self._state
        self.invoke_state_entry_actions(self._state)
        self._current_record.processing_time = time.monotonic() - start_time
        self.store_current_record() 
Example 23
Project: rift-python   Author: brunorijsman   File: fsm.py    License: Apache License 2.0 5 votes vote down vote up
def push_event(self, event, event_data=None):
        fsm = self
        event_tuple = (fsm, event, event_data, time.monotonic())
        if self._current_record is not None:
            # We are pushing an event to an FSM which is in the middle of executing a transaction.
            # We conclude that the FSM is executing an action which pushes an event back to the same
            # FSM instance, hence it is a chained event. (This logic only holds in a single-threaded
            # application, which is what we currently have.)
            self._chained_event_queue.append(event_tuple)
            self._current_record.actions_and_pushed_events.append(event.name)
        else:
            # Normal (external) event
            self._event_queue.append(event_tuple)
            verbose = (event in self._verbose_events)
            self.info_or_debug(verbose, "FSM push event, event=%s", event.name) 
Example 24
Project: rift-python   Author: brunorijsman   File: fsm.py    License: Apache License 2.0 5 votes vote down vote up
def process_event(self, event, event_data, schedule_time):
        assert self._current_record is None
        self._event_counters[event].increase()
        from_state = self._state
        verbose = (event in self._verbose_events)
        queue_time = time.monotonic() - schedule_time
        self._current_record = FsmRecord(self, from_state, event, verbose, queue_time)
        start_time = time.monotonic()
        if from_state in self._transitions:
            from_state_transitions = self._transitions[from_state]
        else:
            from_state_transitions = []
        if event in from_state_transitions:
            transition = from_state_transitions[event]
            (to_state, actions, push_events) = FsmDefinition.parse_transition(transition)
            self.invoke_actions(actions, event_data)
            for push_event in push_events:
                self.push_event(push_event, None)
            if to_state is not None:
                self._current_record.to_state = to_state
                if to_state != self._state:
                    self.invoke_state_exit_actions(self._state)
                    self._state = to_state
                    self.invoke_state_entry_actions(to_state)
        else:
            self._current_record.implicit = True
        self._current_record.processing_time = time.monotonic() - start_time
        self.store_current_record() 
Example 25
Project: rift-python   Author: brunorijsman   File: timer.py    License: Apache License 2.0 5 votes vote down vote up
def now(self):
        return time.monotonic() 
Example 26
Project: loaner   Author: google   File: fake_monotonic.py    License: Apache License 2.0 5 votes vote down vote up
def monotonic():
  global _LAST_TICK
  _LAST_TICK = max(_LAST_TICK, time.time())
  return _LAST_TICK 
Example 27
Project: tornado-zh   Author: tao12345666333   File: ioloop.py    License: MIT License 5 votes vote down vote up
def time(self):
        """Returns the current time according to the `IOLoop`'s clock.

        The return value is a floating-point number relative to an
        unspecified time in the past.

        By default, the `IOLoop`'s time function is `time.time`.  However,
        it may be configured to use e.g. `time.monotonic` instead.
        Calls to `add_timeout` that pass a number instead of a
        `datetime.timedelta` should use this function to compute the
        appropriate time, so they can work no matter what time function
        is chosen.
        """
        return time.time() 
Example 28
Project: tornado-zh   Author: tao12345666333   File: ioloop.py    License: MIT License 5 votes vote down vote up
def time(self):
        """Returns the current time according to the `IOLoop`'s clock.

        The return value is a floating-point number relative to an
        unspecified time in the past.

        By default, the `IOLoop`'s time function is `time.time`.  However,
        it may be configured to use e.g. `time.monotonic` instead.
        Calls to `add_timeout` that pass a number instead of a
        `datetime.timedelta` should use this function to compute the
        appropriate time, so they can work no matter what time function
        is chosen.
        """
        return time.time() 
Example 29
Project: qutebrowser   Author: qutebrowser   File: throttle.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _call_pending(self) -> None:
        """Start a pending call."""
        assert self._pending_call is not None
        self._func(*self._pending_call.args, **self._pending_call.kwargs)
        self._pending_call = None
        self._last_call_ms = int(time.monotonic() * 1000) 
Example 30
Project: olympe   Author: Parrot-Developers   File: expectations.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def as_completed(self, timeout=None):
        end_time = None
        if timeout is not None:
            end_time = timeout + time.monotonic()
        done = set()
        while end_time is None or end_time > time.monotonic():
            fs = OrderedDict([(e._future, e) for e in self.expectations if e not in done])
            for f in as_completed(fs.keys(), timeout=timeout):
                yield fs[f]
                done.add(fs[f])
            if len(done) == len(self.expectations):
                break