Python os.times() Examples

The following are code examples for showing how to use os.times(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: __init__.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def cpu_times(percpu=False):
    """Return system-wide CPU times as a namedtuple.
    Every CPU time represents the seconds the CPU has spent in the given mode.
    The namedtuple's fields availability varies depending on the platform:
     - user
     - system
     - idle
     - nice (UNIX)
     - iowait (Linux)
     - irq (Linux, FreeBSD)
     - softirq (Linux)
     - steal (Linux >= 2.6.11)
     - guest (Linux >= 2.6.24)
     - guest_nice (Linux >= 3.2.0)

    When percpu is True return a list of namedtuples for each CPU.
    First element of the list refers to first CPU, second element
    to second CPU and so on.
    The order of the list is consistent across calls.
    """
    if not percpu:
        return _psplatform.cpu_times()
    else:
        return _psplatform.per_cpu_times() 
Example 2
Project: NiujiaoDebugger   Author: MrSrc   File: test_os.py    GNU General Public License v3.0 6 votes vote down vote up
def test_times(self):
        times = os.times()
        self.assertIsInstance(times, os.times_result)

        for field in ('user', 'system', 'children_user', 'children_system',
                      'elapsed'):
            value = getattr(times, field)
            self.assertIsInstance(value, float)

        if os.name == 'nt':
            self.assertEqual(times.children_user, 0)
            self.assertEqual(times.children_system, 0)
            self.assertEqual(times.elapsed, 0)


# Only test if the C version is provided, otherwise TestPEP519 already tested
# the pure Python implementation. 
Example 3
Project: sympyle   Author: harveyslash   File: test_node.py    GNU General Public License v3.0 6 votes vote down vote up
def test_graph_draw(self):
        """
        Test graph drawing functionality.
        The test passes if the graph image was successfully created.
        """
        a = Tensor(np.random.randn(5))
        b = Tensor(np.random.randn(5))

        o = a + b

        fname = str(hash(os.times())) + ".png"
        full_name = os.path.join(tempfile.gettempdir(), fname)

        o.draw_graph(full_name)
        assert os.path.exists(full_name)
        os.remove(full_name) 
Example 4
Project: pilot2   Author: PanDAWMS   File: jobdata.py    Apache License 2.0 6 votes vote down vote up
def add_size(self, size):
        """
        Add a size measurement to the sizes field at the current time stamp.
        A size measurement is in Bytes.

        :param size: size of object in Bytes (int).
        :return:
        """

        # is t0 set? if not, set it
        if not self.t0:
            self.t0 = os.times()

        # get the current time stamp relative to t0
        time_stamp = get_elapsed_real_time(t0=self.t0)

        # add a data point to the sizes dictionary
        self.sizes[time_stamp] = size 
Example 5
Project: pilot2   Author: PanDAWMS   File: timing.py    Apache License 2.0 6 votes vote down vote up
def get_elapsed_real_time(t0=None):
    """
    Return a time stamp corresponding to the elapsed real time (since t0 if requested).
    The function uses os.times() to get the current time stamp.
    If t0 is provided, the returned time stamp is relative to t0. t0 is assumed to be an os.times() tuple.

    :param t0: os.times() tuple for the t0 time stamp.
    :return: time stamp (int).
    """

    if t0 and type(t0) == tuple:
        try:
            _t0 = int(t0[4])
        except Exception as e:
            logger.warning('unknown timing format for t0: %s' % e)
            _t0 = 0
    else:
        _t0 = 0

    t = int(os.times()[4])

    return t - _t0 
Example 6
Project: Jsdir   Author: Lopseg   File: jsdir_linux.py    GNU General Public License v3.0 6 votes vote down vote up
def jsbeautify(self,host):
      filename = str(os.times()[4])+"-"+host+".js"
      cmd = subprocess.Popen("js-beautify "+PATH_TMP_FILE,shell=True,stdin=subprocess.PIPE,stderr=subprocess.PIPE,stdout=subprocess.PIPE)
      error_output = cmd.stderr.read()
      if "js-beautify: command not found" in error_output or "js-beautify: not found" in error_output:
          print 'In order to jsbeautifier feature work properly, install jsbeatifier on your system with the following commands:\n'
          print 'sudo apt-get install jsbeautifier && pip install jsbeautifier'
          print "Please check if you can run it on the terminal first"
          return
      try:
              self.save_to_file(filename,cmd.stdout.read())
              print "A version of this js file has been beautified and saved at\n "+os.getcwd()+"db/files-beatified/"+filename
      except:
              print "Error in writing to file at "+os.getcwd()+"db/files-beatified/"+filename
              print "Please check the write permissions of the folder/user"
      return 
Example 7
Project: vnpy_crypto   Author: birforce   File: __init__.py    MIT License 6 votes vote down vote up
def _cpu_tot_time(times):
    """Given a cpu_time() ntuple calculates the total CPU time
    (including idle time).
    """
    tot = sum(times)
    if LINUX:
        # On Linux guest times are already accounted in "user" or
        # "nice" times, so we subtract them from total.
        # Htop does the same. References:
        # https://github.com/giampaolo/psutil/pull/940
        # http://unix.stackexchange.com/questions/178045
        # https://github.com/torvalds/linux/blob/
        #     447976ef4fd09b1be88b316d1a81553f1aa7cd07/kernel/sched/
        #     cputime.c#L158
        tot -= getattr(times, "guest", 0)  # Linux 2.6.24+
        tot -= getattr(times, "guest_nice", 0)  # Linux 3.2.0+
    return tot 
Example 8
Project: vnpy_crypto   Author: birforce   File: test_process.py    MIT License 6 votes vote down vote up
def test_cmdline(self):
        cmdline = [PYTHON_EXE, "-c", "import time; time.sleep(60)"]
        sproc = get_test_subprocess(cmdline)
        try:
            self.assertEqual(' '.join(psutil.Process(sproc.pid).cmdline()),
                             ' '.join(cmdline))
        except AssertionError:
            # XXX - most of the times the underlying sysctl() call on Net
            # and Open BSD returns a truncated string.
            # Also /proc/pid/cmdline behaves the same so it looks
            # like this is a kernel bug.
            # XXX - AIX truncates long arguments in /proc/pid/cmdline
            if NETBSD or OPENBSD or AIX:
                self.assertEqual(
                    psutil.Process(sproc.pid).cmdline()[0], PYTHON_EXE)
            else:
                raise 
Example 9
Project: ZOGY   Author: pmvreeswijk   File: zogy.py    MIT License 6 votes vote down vote up
def prep_ds9regions(filename, x, y, radius=5, width=2, color='green',
                    text='id'):

    """Function that creates a text file with the name [filename] that
    can be used to mark objects at an array of pixel positions (x,y)
    with a circle when displaying an image with ds9."""

    # prepare ds9 region file
    f = open(filename, 'w')
    ncoords = len(x)
    for i in range(ncoords):
        if text == 'id':
            f.write('circle({},{},{}) # color={} width={} text={{{}}} font="times 7"\n'.
                    format(x[i], y[i], radius, color, width, i+1))
        else:
            f.write('circle({},{},{}) # color={} width={}\n'.
                    format(x[i], y[i], radius, color, width))            
            
    f.close()
    return
    

################################################################################ 
Example 10
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_os.py    GNU General Public License v2.0 6 votes vote down vote up
def test_times(self):
        times = os.times()
        self.assertIsInstance(times, os.times_result)

        for field in ('user', 'system', 'children_user', 'children_system',
                      'elapsed'):
            value = getattr(times, field)
            self.assertIsInstance(value, float)

        if os.name == 'nt':
            self.assertEqual(times.children_user, 0)
            self.assertEqual(times.children_system, 0)
            self.assertEqual(times.elapsed, 0)


# Only test if the C version is provided, otherwise TestPEP519 already tested
# the pure Python implementation. 
Example 11
Project: teleport   Author: tp4a   File: __init__.py    Apache License 2.0 6 votes vote down vote up
def _cpu_tot_time(times):
    """Given a cpu_time() ntuple calculates the total CPU time
    (including idle time).
    """
    tot = sum(times)
    if LINUX:
        # On Linux guest times are already accounted in "user" or
        # "nice" times, so we subtract them from total.
        # Htop does the same. References:
        # https://github.com/giampaolo/psutil/pull/940
        # http://unix.stackexchange.com/questions/178045
        # https://github.com/torvalds/linux/blob/
        #     447976ef4fd09b1be88b316d1a81553f1aa7cd07/kernel/sched/
        #     cputime.c#L158
        tot -= getattr(times, "guest", 0)  # Linux 2.6.24+
        tot -= getattr(times, "guest_nice", 0)  # Linux 3.2.0+
    return tot 
Example 12
Project: teleport   Author: tp4a   File: test_process.py    Apache License 2.0 6 votes vote down vote up
def test_cmdline(self):
        cmdline = [PYTHON_EXE, "-c", "import time; time.sleep(60)"]
        sproc = get_test_subprocess(cmdline)
        try:
            self.assertEqual(' '.join(psutil.Process(sproc.pid).cmdline()),
                             ' '.join(cmdline))
        except AssertionError:
            # XXX - most of the times the underlying sysctl() call on Net
            # and Open BSD returns a truncated string.
            # Also /proc/pid/cmdline behaves the same so it looks
            # like this is a kernel bug.
            # XXX - AIX truncates long arguments in /proc/pid/cmdline
            if NETBSD or OPENBSD or AIX:
                self.assertEqual(
                    psutil.Process(sproc.pid).cmdline()[0], PYTHON_EXE)
            else:
                raise 
Example 13
Project: teleport   Author: tp4a   File: __init__.py    Apache License 2.0 6 votes vote down vote up
def _cpu_tot_time(times):
    """Given a cpu_time() ntuple calculates the total CPU time
    (including idle time).
    """
    tot = sum(times)
    if LINUX:
        # On Linux guest times are already accounted in "user" or
        # "nice" times, so we subtract them from total.
        # Htop does the same. References:
        # https://github.com/giampaolo/psutil/pull/940
        # http://unix.stackexchange.com/questions/178045
        # https://github.com/torvalds/linux/blob/
        #     447976ef4fd09b1be88b316d1a81553f1aa7cd07/kernel/sched/
        #     cputime.c#L158
        tot -= getattr(times, "guest", 0)  # Linux 2.6.24+
        tot -= getattr(times, "guest_nice", 0)  # Linux 3.2.0+
    return tot 
Example 14
Project: teleport   Author: tp4a   File: __init__.py    Apache License 2.0 6 votes vote down vote up
def _cpu_times_deltas(t1, t2):
    assert t1._fields == t2._fields, (t1, t2)
    field_deltas = []
    for field in _psplatform.scputimes._fields:
        field_delta = getattr(t2, field) - getattr(t1, field)
        # CPU times are always supposed to increase over time
        # or at least remain the same and that's because time
        # cannot go backwards.
        # Surprisingly sometimes this might not be the case (at
        # least on Windows and Linux), see:
        # https://github.com/giampaolo/psutil/issues/392
        # https://github.com/giampaolo/psutil/issues/645
        # https://github.com/giampaolo/psutil/issues/1210
        # Trim negative deltas to zero to ignore decreasing fields.
        # top does the same. Reference:
        # https://gitlab.com/procps-ng/procps/blob/v3.3.12/top/top.c#L5063
        field_delta = max(0, field_delta)
        field_deltas.append(field_delta)
    return _psplatform.scputimes(*field_deltas) 
Example 15
Project: teleport   Author: tp4a   File: __init__.py    Apache License 2.0 6 votes vote down vote up
def _cpu_tot_time(times):
    """Given a cpu_time() ntuple calculates the total CPU time
    (including idle time).
    """
    tot = sum(times)
    if LINUX:
        # On Linux guest times are already accounted in "user" or
        # "nice" times, so we subtract them from total.
        # Htop does the same. References:
        # https://github.com/giampaolo/psutil/pull/940
        # http://unix.stackexchange.com/questions/178045
        # https://github.com/torvalds/linux/blob/
        #     447976ef4fd09b1be88b316d1a81553f1aa7cd07/kernel/sched/
        #     cputime.c#L158
        tot -= getattr(times, "guest", 0)  # Linux 2.6.24+
        tot -= getattr(times, "guest_nice", 0)  # Linux 3.2.0+
    return tot 
Example 16
Project: teleport   Author: tp4a   File: __init__.py    Apache License 2.0 6 votes vote down vote up
def _cpu_times_deltas(t1, t2):
    assert t1._fields == t2._fields, (t1, t2)
    field_deltas = []
    for field in _psplatform.scputimes._fields:
        field_delta = getattr(t2, field) - getattr(t1, field)
        # CPU times are always supposed to increase over time
        # or at least remain the same and that's because time
        # cannot go backwards.
        # Surprisingly sometimes this might not be the case (at
        # least on Windows and Linux), see:
        # https://github.com/giampaolo/psutil/issues/392
        # https://github.com/giampaolo/psutil/issues/645
        # https://github.com/giampaolo/psutil/issues/1210
        # Trim negative deltas to zero to ignore decreasing fields.
        # top does the same. Reference:
        # https://gitlab.com/procps-ng/procps/blob/v3.3.12/top/top.c#L5063
        field_delta = max(0, field_delta)
        field_deltas.append(field_delta)
    return _psplatform.scputimes(*field_deltas) 
Example 17
Project: eden   Author: facebookexperimental   File: run-tests.py    GNU General Public License v2.0 6 votes vote down vote up
def stopTest(self, test, interrupted=False):
        super(TestResult, self).stopTest(test)

        test.stopped = os.times()

        starttime = test.started
        endtime = test.stopped
        origin = self._firststarttime
        self.times.append(
            (
                test.name,
                endtime[2] - starttime[2],  # user space CPU time
                endtime[3] - starttime[3],  # sys  space CPU time
                endtime[4] - starttime[4],  # real time
                starttime[4] - origin,  # start date in run context
                endtime[4] - origin,  # end date in run context
            )
        )

        if interrupted:
            with iolock:
                self.stream.writeln(
                    "INTERRUPTED: %s (after %d seconds)"
                    % (test.name, self.times[-1][3])
                ) 
Example 18
Project: pyblish-win   Author: pyblish   File: profile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _get_time_times(timer=os.times):
        t = timer()
        return t[0] + t[1]

# Using getrusage(3) is better than clock(3) if available:
# on some systems (e.g. FreeBSD), getrusage has a higher resolution
# Furthermore, on a POSIX system, returns microseconds, which
# wrap around after 36min. 
Example 19
Project: pyblish-win   Author: pyblish   File: __init__.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def threads(self):
        """Return threads opened by process as a list of
        (id, user_time, system_time) namedtuples representing
        thread id and thread CPU times (user/system).
        """
        return self._proc.threads() 
Example 20
Project: pyblish-win   Author: pyblish   File: __init__.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def cpu_times(self):
        """Return a (user, system) namedtuple representing  the
        accumulated process time, in seconds.
        This is the same as os.times() but per-process.
        """
        return self._proc.cpu_times() 
Example 21
Project: ipmisim   Author: rhtyd   File: fakesession.py    Apache License 2.0 5 votes vote down vote up
def _monotonic_time():
    return os.times()[4] 
Example 22
Project: ngo-addons-backport   Author: camptocamp   File: web_services.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def exp_get_os_time(self):
        return os.times() 
Example 23
Project: NiujiaoDebugger   Author: MrSrc   File: test_os.py    GNU General Public License v3.0 5 votes vote down vote up
def test_utime_by_indexed(self):
        # pass times as floating point seconds as the second indexed parameter
        def set_time(filename, ns):
            atime_ns, mtime_ns = ns
            atime = self.ns_to_sec(atime_ns)
            mtime = self.ns_to_sec(mtime_ns)
            # test utimensat(timespec), utimes(timeval), utime(utimbuf)
            # or utime(time_t)
            os.utime(filename, (atime, mtime))
        self._test_utime(set_time) 
Example 24
Project: NiujiaoDebugger   Author: MrSrc   File: test_os.py    GNU General Public License v3.0 5 votes vote down vote up
def test_utime_by_times(self):
        def set_time(filename, ns):
            atime_ns, mtime_ns = ns
            atime = self.ns_to_sec(atime_ns)
            mtime = self.ns_to_sec(mtime_ns)
            # test the times keyword parameter
            os.utime(filename, times=(atime, mtime))
        self._test_utime(set_time) 
Example 25
Project: NiujiaoDebugger   Author: MrSrc   File: test_os.py    GNU General Public License v3.0 5 votes vote down vote up
def test_fd_leak(self):
        # Since we're opening a lot of FDs, we must be careful to avoid leaks:
        # we both check that calling fwalk() a large number of times doesn't
        # yield EMFILE, and that the minimum allocated FD hasn't changed.
        minfd = os.dup(1)
        os.close(minfd)
        for i in range(256):
            for x in self.fwalk(support.TESTFN):
                pass
        newfd = os.dup(1)
        self.addCleanup(os.close, newfd)
        self.assertEqual(newfd, minfd) 
Example 26
Project: NiujiaoDebugger   Author: MrSrc   File: iobench.py    GNU General Public License v3.0 5 votes vote down vote up
def run_during(duration, func):
    _t = time.time
    n = 0
    start = os.times()
    start_timestamp = _t()
    real_start = start[4] or start_timestamp
    while True:
        func()
        n += 1
        if _t() - start_timestamp > duration:
            break
    end = os.times()
    real = (end[4] if start[4] else time.time()) - real_start
    return n, real, sum(end[0:2]) - sum(start[0:2]) 
Example 27
Project: errbot-chatopsanything   Author: andrewthetechie   File: chatops-anything.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, bot, name: str = None) -> None:
        """
        Calls super init and adds a few plugin variables of our own. This makes PEP8 happy
        """
        super().__init__(bot, name)
        # HASH is used to identify the plugin and for uniqueness
        # generate a md5 hash of os.times() and grab 10 characters of it, just for easy uniqueness
        self.HASH = md5(f"{os.times()}".encode("utf-8")).hexdigest()[:10]
        self.BIN_PATH = None  # typing: Path
        self.CONFIG_PATH = None  # typing: Path
        self.TEMP_PATH = None  # typing: Path
        self.EXECUTABLE_CONFIGS = {}  # typing: Dict
        self.log.debug("Done with init")

    # botplugin methods, these are not commands and just configure/setup our plugin 
Example 28
Project: tsinfer   Author: tskit-dev   File: cli.py    GNU General Public License v3.0 5 votes vote down vote up
def summarise_usage():
    wall_time = humanize.naturaldelta(time.time() - __before)
    user_time = humanize.naturaldelta(os.times().user)
    sys_time = os.times().system
    if resource is None:
        # Don't report max memory on Windows. We could do this using the psutil lib, via
        # psutil.Process(os.getpid()).get_ext_memory_info().peak_wset if demand exists
        maxmem_str = ""
    else:
        max_mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
        if sys.platform != 'darwin':
            max_mem *= 1024  # Linux and other OSs (e.g. freeBSD) report maxrss in kb
        maxmem_str = "; max memory={}".format(humanize.naturalsize(max_mem, binary=True))
    logger.info("wall time = {}".format(wall_time))
    logger.info("rusage: user={}; sys={:.2f}s".format(user_time, sys_time) + maxmem_str) 
Example 29
Project: pilot2   Author: PanDAWMS   File: processes.py    Apache License 2.0 5 votes vote down vote up
def get_cpu_consumption_time(t0):
    """
    Return the CPU consumption time for child processes measured by system+user time from os.times().
    Note: the os.times() tuple is user time, system time, s user time, s system time, and elapsed real time since a
    fixed point in the past.

    :param t0: initial os.times() tuple prior to measurement.
    :return: system+user time for child processes (float).
    """

    t1 = os.times()
    user_time = t1[2] - t0[2]
    system_time = t1[3] - t0[3]

    return user_time + system_time 
Example 30
Project: pilot2   Author: PanDAWMS   File: processes.py    Apache License 2.0 5 votes vote down vote up
def get_instant_cpu_consumption_time(pid):
    """
    Return the CPU consumption time (system+user time) for a given process, by parsing /prod/pid/stat.
    Note 1: the function returns 0.0 if the pid is not set.
    Note 2: the function must sum up all the user+system times for both the main process (pid) and the child
    processes, since the main process is most likely spawning new processes.

    :param pid: process id (int).
    :return: system+user time for a given pid (float).
    """

    utime = None
    stime = None
    cutime = None
    cstime = None

    hz = os.sysconf(os.sysconf_names['SC_CLK_TCK'])
    if type(hz) != int:
        logger.warning('unknown SC_CLK_TCK: %s' % str(hz))
        return 0.0

    if pid and hz and hz > 0:
        path = "/proc/%d/stat" % pid
        if os.path.exists(path):
            with open(path) as fp:
                fields = fp.read().split(' ')[13:17]
                utime, stime, cutime, cstime = [(float(f) / hz) for f in fields]

    if utime and stime and cutime and cstime:
        # sum up all the user+system times for both the main process (pid) and the child processes
        cpu_consumption_time = utime + stime + cutime + cstime
    else:
        cpu_consumption_time = 0.0

    return cpu_consumption_time 
Example 31
Project: crow   Author: acopar   File: utils.py    GNU General Public License v3.0 5 votes vote down vote up
def time(self):
        if self.system == False:
            return time.time()
        else:
            return os.times()[4] 
Example 32
Project: rpython-lang-scheme   Author: tomoh1r   File: test_ll_os.py    MIT License 5 votes vote down vote up
def test_times():
    """
    posix.times should compile as an RPython function and should return a
    five-tuple giving float-representations (seconds, effectively) of the four
    fields from the underlying struct tms and the return value.
    """
    times = eval(compile(lambda: str(os.times()), ())())
    assert isinstance(times, tuple)
    assert len(times) == 5
    for value in times:
        assert isinstance(value, float) 
Example 33
Project: ironpython2   Author: IronLanguages   File: profile.py    Apache License 2.0 5 votes vote down vote up
def _get_time_times(timer=os.times):
        t = timer()
        return t[0] + t[1]

# Using getrusage(3) is better than clock(3) if available:
# on some systems (e.g. FreeBSD), getrusage has a higher resolution
# Furthermore, on a POSIX system, returns microseconds, which
# wrap around after 36min. 
Example 34
Project: how-to-cython-mt2   Author: martysama0134   File: Timing.py    MIT License 5 votes vote down vote up
def time():
    t = os.times()
    return t[0] + t[1] 
Example 35
Project: fast-nmtf   Author: acopar   File: common.py    GNU General Public License v3.0 5 votes vote down vote up
def time(self):
        if self.system == False:
            return time.time()
        else:
            return os.times()[4] 
Example 36
Project: vnpy_crypto   Author: birforce   File: __init__.py    MIT License 5 votes vote down vote up
def threads(self):
            """Return threads opened by process as a list of
            (id, user_time, system_time) namedtuples representing
            thread id and thread CPU times (user/system).
            On OpenBSD this method requires root access.
            """
            return self._proc.threads() 
Example 37
Project: vnpy_crypto   Author: birforce   File: __init__.py    MIT License 5 votes vote down vote up
def cpu_times(self):
        """Return a (user, system, children_user, children_system)
        namedtuple representing the accumulated process time, in
        seconds.
        This is similar to os.times() but per-process.
        On OSX and Windows children_user and children_system are
        always set to 0.
        """
        return self._proc.cpu_times() 
Example 38
Project: vnpy_crypto   Author: birforce   File: __init__.py    MIT License 5 votes vote down vote up
def cpu_times(percpu=False):
    """Return system-wide CPU times as a namedtuple.
    Every CPU time represents the seconds the CPU has spent in the
    given mode. The namedtuple's fields availability varies depending on the
    platform:

     - user
     - system
     - idle
     - nice (UNIX)
     - iowait (Linux)
     - irq (Linux, FreeBSD)
     - softirq (Linux)
     - steal (Linux >= 2.6.11)
     - guest (Linux >= 2.6.24)
     - guest_nice (Linux >= 3.2.0)

    When *percpu* is True return a list of namedtuples for each CPU.
    First element of the list refers to first CPU, second element
    to second CPU and so on.
    The order of the list is consistent across calls.
    """
    if not percpu:
        return _psplatform.cpu_times()
    else:
        return _psplatform.per_cpu_times() 
Example 39
Project: vnpy_crypto   Author: birforce   File: __init__.py    MIT License 5 votes vote down vote up
def _cpu_busy_time(times):
    """Given a cpu_time() ntuple calculates the busy CPU time.
    We do so by subtracting all idle CPU times.
    """
    busy = _cpu_tot_time(times)
    busy -= times.idle
    # Linux: "iowait" is time during which the CPU does not do anything
    # (waits for IO to complete). On Linux IO wait is *not* accounted
    # in "idle" time so we subtract it. Htop does the same.
    # References:
    # https://github.com/torvalds/linux/blob/
    #     447976ef4fd09b1be88b316d1a81553f1aa7cd07/kernel/sched/cputime.c#L244
    busy -= getattr(times, "iowait", 0)
    return busy 
Example 40
Project: vnpy_crypto   Author: birforce   File: test_process.py    MIT License 5 votes vote down vote up
def test_cpu_times(self):
        times = psutil.Process().cpu_times()
        assert (times.user > 0.0) or (times.system > 0.0), times
        assert (times.children_user >= 0.0), times
        assert (times.children_system >= 0.0), times
        # make sure returned values can be pretty printed with strftime
        for name in times._fields:
            time.strftime("%H:%M:%S", time.localtime(getattr(times, name))) 
Example 41
Project: vnpy_crypto   Author: birforce   File: test_process.py    MIT License 5 votes vote down vote up
def test_cpu_times_2(self):
        user_time, kernel_time = psutil.Process().cpu_times()[:2]
        utime, ktime = os.times()[:2]

        # Use os.times()[:2] as base values to compare our results
        # using a tolerance  of +/- 0.1 seconds.
        # It will fail if the difference between the values is > 0.1s.
        if (max([user_time, utime]) - min([user_time, utime])) > 0.1:
            self.fail("expected: %s, found: %s" % (utime, user_time))

        if (max([kernel_time, ktime]) - min([kernel_time, ktime])) > 0.1:
            self.fail("expected: %s, found: %s" % (ktime, kernel_time)) 
Example 42
Project: Blockly-rduino-communication   Author: technologiescollege   File: profile.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, timer=None, bias=None):
        self.timings = {}
        self.cur = None
        self.cmd = ""
        self.c_func_name = ""

        if bias is None:
            bias = self.bias
        self.bias = bias     # Materialize in local dict for lookup speed.

        if not timer:
            self.timer = self.get_time = time.process_time
            self.dispatcher = self.trace_dispatch_i
        else:
            self.timer = timer
            t = self.timer() # test out timer function
            try:
                length = len(t)
            except TypeError:
                self.get_time = timer
                self.dispatcher = self.trace_dispatch_i
            else:
                if length == 2:
                    self.dispatcher = self.trace_dispatch
                else:
                    self.dispatcher = self.trace_dispatch_l
                # This get_time() implementation needs to be defined
                # here to capture the passed-in timer in the parameter
                # list (for performance).  Note that we can't assume
                # the timer() result contains two values in all
                # cases.
                def get_time_timer(timer=timer, sum=sum):
                    return sum(timer())
                self.get_time = get_time_timer
        self.t = self.get_time()
        self.simulate_call('profiler')

    # Heavily optimized dispatch routine for os.times() timer 
Example 43
Project: IronHydra   Author: microdee   File: profile.py    MIT License 5 votes vote down vote up
def _get_time_times(timer=os.times):
        t = timer()
        return t[0] + t[1]

# Using getrusage(3) is better than clock(3) if available:
# on some systems (e.g. FreeBSD), getrusage has a higher resolution
# Furthermore, on a POSIX system, returns microseconds, which
# wrap around after 36min. 
Example 44
Project: Auklet-Agent-Python   Author: aukletio   File: statprof.py    Apache License 2.0 5 votes vote down vote up
def clock():
    times = os.times()
    return times[0] + times[1]


###########################################################################
# Collection data structures 
Example 45
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_os.py    GNU General Public License v2.0 5 votes vote down vote up
def test_utime_by_indexed(self):
        # pass times as floating point seconds as the second indexed parameter
        def set_time(filename, ns):
            atime_ns, mtime_ns = ns
            atime = self.ns_to_sec(atime_ns)
            mtime = self.ns_to_sec(mtime_ns)
            # test utimensat(timespec), utimes(timeval), utime(utimbuf)
            # or utime(time_t)
            os.utime(filename, (atime, mtime))
        self._test_utime(set_time) 
Example 46
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_os.py    GNU General Public License v2.0 5 votes vote down vote up
def test_utime_by_times(self):
        def set_time(filename, ns):
            atime_ns, mtime_ns = ns
            atime = self.ns_to_sec(atime_ns)
            mtime = self.ns_to_sec(mtime_ns)
            # test the times keyword parameter
            os.utime(filename, times=(atime, mtime))
        self._test_utime(set_time) 
Example 47
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_os.py    GNU General Public License v2.0 5 votes vote down vote up
def test_fd_leak(self):
        # Since we're opening a lot of FDs, we must be careful to avoid leaks:
        # we both check that calling fwalk() a large number of times doesn't
        # yield EMFILE, and that the minimum allocated FD hasn't changed.
        minfd = os.dup(1)
        os.close(minfd)
        for i in range(256):
            for x in self.fwalk(support.TESTFN):
                pass
        newfd = os.dup(1)
        self.addCleanup(os.close, newfd)
        self.assertEqual(newfd, minfd) 
Example 48
Project: aws-lambda-runtime-pypy   Author: uscheller   File: profile.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, timer=None, bias=None):
        self.timings = {}
        self.cur = None
        self.cmd = ""
        self.c_func_name = ""

        if bias is None:
            bias = self.bias
        self.bias = bias     # Materialize in local dict for lookup speed.

        if not timer:
            self.timer = self.get_time = time.process_time
            self.dispatcher = self.trace_dispatch_i
        else:
            self.timer = timer
            t = self.timer() # test out timer function
            try:
                length = len(t)
            except TypeError:
                self.get_time = timer
                self.dispatcher = self.trace_dispatch_i
            else:
                if length == 2:
                    self.dispatcher = self.trace_dispatch
                else:
                    self.dispatcher = self.trace_dispatch_l
                # This get_time() implementation needs to be defined
                # here to capture the passed-in timer in the parameter
                # list (for performance).  Note that we can't assume
                # the timer() result contains two values in all
                # cases.
                def get_time_timer(timer=timer, sum=sum):
                    return sum(timer())
                self.get_time = get_time_timer
        self.t = self.get_time()
        self.simulate_call('profiler')

    # Heavily optimized dispatch routine for os.times() timer 
Example 49
Project: Computable   Author: ktraunmueller   File: profile.py    MIT License 5 votes vote down vote up
def _get_time_times(timer=os.times):
        t = timer()
        return t[0] + t[1]

# Using getrusage(3) is better than clock(3) if available:
# on some systems (e.g. FreeBSD), getrusage has a higher resolution
# Furthermore, on a POSIX system, returns microseconds, which
# wrap around after 36min. 
Example 50
Project: FOLLOW   Author: adityagilra   File: input_ff_rec_robot_nengo_directu_ocl.py    GNU General Public License v3.0 5 votes vote down vote up
def sim_run_flush(tFlush,nFlush):
        '''
            Run simulation for nFlush*tFlush seconds,
            Flush probes every tFlush of simulation time,
              (only flush those that don't have 'weights' in their label names)
        '''        
        weighttimeidxold = 0
        #doubledLearningRate = False
        for duration in [tFlush]*nFlush:
            _,_,_,_,realtime = os.times()
            print("Finished till",sim.time,'s, in',realtime-realtimeold,'s')
            sys.stdout.flush()
            # save weights if weightdt or more has passed since last save
            weighttimeidx = int(sim.time/weightdt)
            if weighttimeidx > weighttimeidxold:
                weighttimeidxold = weighttimeidx
                save_current_weights(False,sim.time)
            # flush probes
            for probe in sim.model.probes:
                # except weight probes (flushed in save_current_weights)
                # except error probe which is saved fully in ..._end.shelve
                if probe.label is not None:
                    if 'weights' in probe.label or 'error' in probe.label:
                        break
                del sim._probe_outputs[probe][:]
            ## if time > 1000s, double learning rate
            #if sim.time>1000. and not doubledLearningRate:
            #    changeLearningRate(4.)  # works only if excPESDecayRate = None
            #    doubledLearningRate = True
            # run simulation for tFlush duration
            sim.run(duration,progress_bar=False)

    ###
    ### run the simulation, with flushing for learning simulations ###
    ### 
Example 51
Project: FOLLOW   Author: adityagilra   File: input_ff_rec_transform_nengo_ocl.py    GNU General Public License v3.0 5 votes vote down vote up
def sim_run_flush(tFlush,nFlush):
        '''
            Run simulation for nFlush*tFlush seconds,
            Flush probes every tFlush of simulation time,
              (only flush those that don't have 'weights' in their label names)
        '''        
        weighttimeidxold = 0
        #doubledLearningRate = False
        for duration in [tFlush]*nFlush:
            _,_,_,_,realtime = os.times()
            print("Finished till",sim.time,'s, in',realtime-realtimeold,'s')
            sys.stdout.flush()
            # save weights if weightdt or more has passed since last save
            weighttimeidx = int(sim.time/weightdt)
            if weighttimeidx > weighttimeidxold:
                weighttimeidxold = weighttimeidx
                save_current_weights(False,sim.time)
            # flush probes
            for probe in sim.model.probes:
                # except weight probes (flushed in save_current_weights)
                # except error probe which is saved fully in ..._end.shelve
                if probe.label is not None:
                    if 'weights' in probe.label or 'error' in probe.label:
                        break
                del sim._probe_outputs[probe][:]
            ## if time > 1000s, double learning rate
            #if sim.time>1000. and not doubledLearningRate:
            #    changeLearningRate(4.)  # works only if excPESDecayRate = None
            #    doubledLearningRate = True
            # run simulation for tFlush duration
            sim.run(duration,progress_bar=False)

    ###
    ### run the simulation, with flushing for learning simulations ###
    ### 
Example 52
Project: FOLLOW   Author: adityagilra   File: input_ff_rec_learnoutput_nengo_ocl.py    GNU General Public License v3.0 5 votes vote down vote up
def sim_run_flush(tFlush,nFlush):
        '''
            Run simulation for nFlush*tFlush seconds,
            Flush probes every tFlush of simulation time,
              (only flush those that don't have 'weights' in their label names)
        '''        
        weighttimeidxold = 0
        #doubledLearningRate = False
        for duration in [tFlush]*nFlush:
            _,_,_,_,realtime = os.times()
            print("Finished till",sim.time,'s, in',realtime-realtimeold,'s')
            sys.stdout.flush()
            # save weights if weightdt or more has passed since last save
            weighttimeidx = int(sim.time/weightdt)
            if weighttimeidx > weighttimeidxold:
                weighttimeidxold = weighttimeidx
                save_current_weights(False,sim.time)
            # flush probes
            for probe in sim.model.probes:
                # except weight probes (flushed in save_current_weights)
                # except error probe which is saved fully in ..._end.shelve
                if probe.label is not None:
                    if 'weights' in probe.label or 'error' in probe.label:
                        break
                del sim._probe_outputs[probe][:]
            ## if time > 1000s, double learning rate
            #if sim.time>1000. and not doubledLearningRate:
            #    changeLearningRate(4.)  # works only if excPESDecayRate = None
            #    doubledLearningRate = True
            # run simulation for tFlush duration
            sim.run(duration,progress_bar=False)

    ###
    ### run the simulation, with flushing for learning simulations ###
    ### 
Example 53
Project: ableton-live-webapi   Author: valsteen   File: Timing.py    The Unlicense 5 votes vote down vote up
def time():
    t = os.times()
    return t[0] + t[1] 
Example 54
Project: oss-ftp   Author: aliyun   File: profile.py    MIT License 5 votes vote down vote up
def _get_time_times(timer=os.times):
        t = timer()
        return t[0] + t[1]

# Using getrusage(3) is better than clock(3) if available:
# on some systems (e.g. FreeBSD), getrusage has a higher resolution
# Furthermore, on a POSIX system, returns microseconds, which
# wrap around after 36min. 
Example 55
Project: teleport   Author: tp4a   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def threads(self):
            """Return threads opened by process as a list of
            (id, user_time, system_time) namedtuples representing
            thread id and thread CPU times (user/system).
            On OpenBSD this method requires root access.
            """
            return self._proc.threads() 
Example 56
Project: teleport   Author: tp4a   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def cpu_times(self):
        """Return a (user, system, children_user, children_system)
        namedtuple representing the accumulated process time, in
        seconds.
        This is similar to os.times() but per-process.
        On macOS and Windows children_user and children_system are
        always set to 0.
        """
        return self._proc.cpu_times() 
Example 57
Project: teleport   Author: tp4a   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def cpu_times(percpu=False):
    """Return system-wide CPU times as a namedtuple.
    Every CPU time represents the seconds the CPU has spent in the
    given mode. The namedtuple's fields availability varies depending on the
    platform:

     - user
     - system
     - idle
     - nice (UNIX)
     - iowait (Linux)
     - irq (Linux, FreeBSD)
     - softirq (Linux)
     - steal (Linux >= 2.6.11)
     - guest (Linux >= 2.6.24)
     - guest_nice (Linux >= 3.2.0)

    When *percpu* is True return a list of namedtuples for each CPU.
    First element of the list refers to first CPU, second element
    to second CPU and so on.
    The order of the list is consistent across calls.
    """
    if not percpu:
        return _psplatform.cpu_times()
    else:
        return _psplatform.per_cpu_times() 
Example 58
Project: teleport   Author: tp4a   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def _cpu_busy_time(times):
    """Given a cpu_time() ntuple calculates the busy CPU time.
    We do so by subtracting all idle CPU times.
    """
    busy = _cpu_tot_time(times)
    busy -= times.idle
    # Linux: "iowait" is time during which the CPU does not do anything
    # (waits for IO to complete). On Linux IO wait is *not* accounted
    # in "idle" time so we subtract it. Htop does the same.
    # References:
    # https://github.com/torvalds/linux/blob/
    #     447976ef4fd09b1be88b316d1a81553f1aa7cd07/kernel/sched/cputime.c#L244
    busy -= getattr(times, "iowait", 0)
    return busy 
Example 59
Project: teleport   Author: tp4a   File: test_process.py    Apache License 2.0 5 votes vote down vote up
def test_cpu_times(self):
        times = psutil.Process().cpu_times()
        assert (times.user > 0.0) or (times.system > 0.0), times
        assert (times.children_user >= 0.0), times
        assert (times.children_system >= 0.0), times
        # make sure returned values can be pretty printed with strftime
        for name in times._fields:
            time.strftime("%H:%M:%S", time.localtime(getattr(times, name))) 
Example 60
Project: teleport   Author: tp4a   File: test_process.py    Apache License 2.0 5 votes vote down vote up
def test_cpu_times_2(self):
        user_time, kernel_time = psutil.Process().cpu_times()[:2]
        utime, ktime = os.times()[:2]

        # Use os.times()[:2] as base values to compare our results
        # using a tolerance  of +/- 0.1 seconds.
        # It will fail if the difference between the values is > 0.1s.
        if (max([user_time, utime]) - min([user_time, utime])) > 0.1:
            self.fail("expected: %s, found: %s" % (utime, user_time))

        if (max([kernel_time, ktime]) - min([kernel_time, ktime])) > 0.1:
            self.fail("expected: %s, found: %s" % (ktime, kernel_time)) 
Example 61
Project: teleport   Author: tp4a   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def threads(self):
            """Return threads opened by process as a list of
            (id, user_time, system_time) namedtuples representing
            thread id and thread CPU times (user/system).
            On OpenBSD this method requires root access.
            """
            return self._proc.threads() 
Example 62
Project: teleport   Author: tp4a   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def cpu_times(self):
        """Return a (user, system, children_user, children_system)
        namedtuple representing the accumulated process time, in
        seconds.
        This is similar to os.times() but per-process.
        On macOS and Windows children_user and children_system are
        always set to 0.
        """
        return self._proc.cpu_times() 
Example 63
Project: teleport   Author: tp4a   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def _cpu_busy_time(times):
    """Given a cpu_time() ntuple calculates the busy CPU time.
    We do so by subtracting all idle CPU times.
    """
    busy = _cpu_tot_time(times)
    busy -= times.idle
    # Linux: "iowait" is time during which the CPU does not do anything
    # (waits for IO to complete). On Linux IO wait is *not* accounted
    # in "idle" time so we subtract it. Htop does the same.
    # References:
    # https://github.com/torvalds/linux/blob/
    #     447976ef4fd09b1be88b316d1a81553f1aa7cd07/kernel/sched/cputime.c#L244
    busy -= getattr(times, "iowait", 0)
    return busy 
Example 64
Project: teleport   Author: tp4a   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def threads(self):
            """Return threads opened by process as a list of
            (id, user_time, system_time) namedtuples representing
            thread id and thread CPU times (user/system).
            On OpenBSD this method requires root access.
            """
            return self._proc.threads() 
Example 65
Project: teleport   Author: tp4a   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def cpu_times(self):
        """Return a (user, system, children_user, children_system)
        namedtuple representing the accumulated process time, in
        seconds.
        This is similar to os.times() but per-process.
        On macOS and Windows children_user and children_system are
        always set to 0.
        """
        return self._proc.cpu_times() 
Example 66
Project: teleport   Author: tp4a   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def _cpu_busy_time(times):
    """Given a cpu_time() ntuple calculates the busy CPU time.
    We do so by subtracting all idle CPU times.
    """
    busy = _cpu_tot_time(times)
    busy -= times.idle
    # Linux: "iowait" is time during which the CPU does not do anything
    # (waits for IO to complete). On Linux IO wait is *not* accounted
    # in "idle" time so we subtract it. Htop does the same.
    # References:
    # https://github.com/torvalds/linux/blob/
    #     447976ef4fd09b1be88b316d1a81553f1aa7cd07/kernel/sched/cputime.c#L244
    busy -= getattr(times, "iowait", 0)
    return busy 
Example 67
Project: setup   Author: mindbender-studio   File: profile.py    MIT License 5 votes vote down vote up
def __init__(self, timer=None, bias=None):
        self.timings = {}
        self.cur = None
        self.cmd = ""
        self.c_func_name = ""

        if bias is None:
            bias = self.bias
        self.bias = bias     # Materialize in local dict for lookup speed.

        if not timer:
            self.timer = self.get_time = time.process_time
            self.dispatcher = self.trace_dispatch_i
        else:
            self.timer = timer
            t = self.timer() # test out timer function
            try:
                length = len(t)
            except TypeError:
                self.get_time = timer
                self.dispatcher = self.trace_dispatch_i
            else:
                if length == 2:
                    self.dispatcher = self.trace_dispatch
                else:
                    self.dispatcher = self.trace_dispatch_l
                # This get_time() implementation needs to be defined
                # here to capture the passed-in timer in the parameter
                # list (for performance).  Note that we can't assume
                # the timer() result contains two values in all
                # cases.
                def get_time_timer(timer=timer, sum=sum):
                    return sum(timer())
                self.get_time = get_time_timer
        self.t = self.get_time()
        self.simulate_call('profiler')

    # Heavily optimized dispatch routine for os.times() timer 
Example 68
Project: eden   Author: facebookexperimental   File: run-tests.py    GNU General Public License v2.0 5 votes vote down vote up
def _hghave(self, reqs):
        # Cache the results of _hghave() checks.
        # In some cases the same _hghave() call can be repeated hundreds of
        # times in a row.  (For instance, if a linematch check with a hghave
        # requirement does not match, the _hghave() call will be repeated for
        # each remaining line in the test output.)
        key = tuple(reqs)
        result = self._hghavecache.get(key)
        if result is None:
            result = self._computehghave(reqs)
            self._hghavecache[key] = result
        return result 
Example 69
Project: eden   Author: facebookexperimental   File: run-tests.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, options, *args, **kwargs):
        super(TestResult, self).__init__(*args, **kwargs)

        self._options = options

        # unittest.TestResult didn't have skipped until 2.7. We need to
        # polyfill it.
        self.skipped = []

        # We have a custom "ignored" result that isn't present in any Python
        # unittest implementation. It is very similar to skipped. It may make
        # sense to map it into skip some day.
        self.ignored = []

        self.times = []
        self._firststarttime = None
        # Data stored for the benefit of generating xunit reports.
        self.successes = []
        self.faildata = {}

        if options.color == "auto":
            self.color = pygmentspresent and self.stream.isatty()
        elif options.color == "never":
            self.color = False
        else:  # 'always', for testing purposes
            self.color = pygmentspresent 
Example 70
Project: eden   Author: facebookexperimental   File: run-tests.py    GNU General Public License v2.0 5 votes vote down vote up
def startTest(self, test):
        super(TestResult, self).startTest(test)

        # os.times module computes the user time and system time spent by
        # child's processes along with real elapsed time taken by a process.
        # This module has one limitation. It can only work for Linux user
        # and not for Windows.
        test.started = os.times()
        if self._firststarttime is None:  # thread racy but irrelevant
            self._firststarttime = test.started[4] 
Example 71
Project: eden   Author: facebookexperimental   File: run-tests.py    GNU General Public License v2.0 5 votes vote down vote up
def loadtimes(outputdir):
    times = []
    try:
        with open(os.path.join(outputdir, b".testtimes-")) as fp:
            for line in fp:
                ts = line.split()
                times.append((ts[0], [float(t) for t in ts[1:]]))
    except IOError as err:
        if err.errno != errno.ENOENT:
            raise
    return times 
Example 72
Project: eden   Author: facebookexperimental   File: run-tests.py    GNU General Public License v2.0 5 votes vote down vote up
def printtimes(self, times):
        # iolock held by run
        self.stream.writeln("# Producing time report")
        times.sort(key=lambda t: (t[3]))
        cols = "%7.3f %7.3f %7.3f %7.3f %7.3f   %s"
        self.stream.writeln(
            "%-7s %-7s %-7s %-7s %-7s   %s"
            % ("start", "end", "cuser", "csys", "real", "Test")
        )
        for tdata in times:
            test = tdata[0]
            cuser, csys, real, start, end = tdata[1:6]
            self.stream.writeln(cols % (start, end, cuser, csys, real, test)) 
Example 73
Project: eden   Author: facebookexperimental   File: run-tests.py    GNU General Public License v2.0 5 votes vote down vote up
def _writejson(result, outf):
        timesd = {}
        for tdata in result.times:
            test = tdata[0]
            timesd[test] = tdata[1:]

        outcome = {}
        groups = [
            ("success", ((tc, None) for tc in result.successes)),
            ("failure", result.failures),
            ("skip", result.skipped),
        ]
        for res, testcases in groups:
            for tc, __ in testcases:
                if tc.name in timesd:
                    diff = result.faildata.get(tc.name, b"")
                    try:
                        diff = diff.decode("unicode_escape")
                    except UnicodeDecodeError as e:
                        diff = "%r decoding diff, sorry" % e
                    tres = {
                        "result": res,
                        "time": ("%0.3f" % timesd[tc.name][2]),
                        "cuser": ("%0.3f" % timesd[tc.name][0]),
                        "csys": ("%0.3f" % timesd[tc.name][1]),
                        "start": ("%0.3f" % timesd[tc.name][3]),
                        "end": ("%0.3f" % timesd[tc.name][4]),
                        "diff": diff,
                    }
                else:
                    # blacklisted test
                    tres = {"result": res}

                outcome[tc.name] = tres
        outf.write(
            json.dumps(outcome, sort_keys=True, indent=4, separators=(",", ": "))
        ) 
Example 74
Project: pyblish-win   Author: pyblish   File: profile.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def __init__(self, timer=None, bias=None):
        self.timings = {}
        self.cur = None
        self.cmd = ""
        self.c_func_name = ""

        if bias is None:
            bias = self.bias
        self.bias = bias     # Materialize in local dict for lookup speed.

        if not timer:
            if _has_res:
                self.timer = resgetrusage
                self.dispatcher = self.trace_dispatch
                self.get_time = _get_time_resource
            elif hasattr(time, 'clock'):
                self.timer = self.get_time = time.clock
                self.dispatcher = self.trace_dispatch_i
            elif hasattr(os, 'times'):
                self.timer = os.times
                self.dispatcher = self.trace_dispatch
                self.get_time = _get_time_times
            else:
                self.timer = self.get_time = time.time
                self.dispatcher = self.trace_dispatch_i
        else:
            self.timer = timer
            t = self.timer() # test out timer function
            try:
                length = len(t)
            except TypeError:
                self.get_time = timer
                self.dispatcher = self.trace_dispatch_i
            else:
                if length == 2:
                    self.dispatcher = self.trace_dispatch
                else:
                    self.dispatcher = self.trace_dispatch_l
                # This get_time() implementation needs to be defined
                # here to capture the passed-in timer in the parameter
                # list (for performance).  Note that we can't assume
                # the timer() result contains two values in all
                # cases.
                def get_time_timer(timer=timer, sum=sum):
                    return sum(timer())
                self.get_time = get_time_timer
        self.t = self.get_time()
        self.simulate_call('profiler')

    # Heavily optimized dispatch routine for os.times() timer 
Example 75
Project: ironpython2   Author: IronLanguages   File: profile.py    Apache License 2.0 4 votes vote down vote up
def __init__(self, timer=None, bias=None):
        self.timings = {}
        self.cur = None
        self.cmd = ""
        self.c_func_name = ""

        if bias is None:
            bias = self.bias
        self.bias = bias     # Materialize in local dict for lookup speed.

        if not timer:
            if _has_res:
                self.timer = resgetrusage
                self.dispatcher = self.trace_dispatch
                self.get_time = _get_time_resource
            elif hasattr(time, 'clock'):
                self.timer = self.get_time = time.clock
                self.dispatcher = self.trace_dispatch_i
            elif hasattr(os, 'times'):
                self.timer = os.times
                self.dispatcher = self.trace_dispatch
                self.get_time = _get_time_times
            else:
                self.timer = self.get_time = time.time
                self.dispatcher = self.trace_dispatch_i
        else:
            self.timer = timer
            t = self.timer() # test out timer function
            try:
                length = len(t)
            except TypeError:
                self.get_time = timer
                self.dispatcher = self.trace_dispatch_i
            else:
                if length == 2:
                    self.dispatcher = self.trace_dispatch
                else:
                    self.dispatcher = self.trace_dispatch_l
                # This get_time() implementation needs to be defined
                # here to capture the passed-in timer in the parameter
                # list (for performance).  Note that we can't assume
                # the timer() result contains two values in all
                # cases.
                def get_time_timer(timer=timer, sum=sum):
                    return sum(timer())
                self.get_time = get_time_timer
        self.t = self.get_time()
        self.simulate_call('profiler')

    # Heavily optimized dispatch routine for os.times() timer 
Example 76
Project: code-inspector   Author: maxim5   File: 4a91107d34c429454e341349d8e18063_pep418.py    Apache License 2.0 4 votes vote down vote up
def _process_time(use_info):
        info = None
        if _process_time.clock_id is not None:
            try:
                return _clock_gettime_info(use_info, _process_time.clock_id)
            except OSError:
                _process_time.clock_id = None
        if _process_time.use_getrusage:
            try:
                usage = resource.getrusage(resource.RUSAGE_SELF)
                value = usage[0] + usage[1]
            except OSError:
                _process_time.use_getrusage = False
            else:
                if use_info:
                    info = {
                        "implementation": "getrusage(RUSAGE_SELF)",
                        "resolution": 1e-6,
                        "monotonic": True,
                        "adjustable": False,
                    }
                return (value, info)
        if _process_time.use_times:
            try:
                times = os.times()
                value = times[0] + times[1]
            except OSError:
                _process_time.use_getrusage = False
            else:
                if use_info:
                    try:
                        ticks_per_second = os.sysconf("SC_CLK_TCK")
                    except ValueError:
                        ticks_per_second = 60 # FIXME: get HZ constant
                    info = {
                        "implementation": "times()",
                        "resolution": 1.0 / ticks_per_second,
                        "monotonic": True,
                        "adjustable": False,
                    }
                return (value, info)
        return _libc_clock_info(use_info) 
Example 77
Project: IronHydra   Author: microdee   File: profile.py    MIT License 4 votes vote down vote up
def __init__(self, timer=None, bias=None):
        self.timings = {}
        self.cur = None
        self.cmd = ""
        self.c_func_name = ""

        if bias is None:
            bias = self.bias
        self.bias = bias     # Materialize in local dict for lookup speed.

        if not timer:
            if _has_res:
                self.timer = resgetrusage
                self.dispatcher = self.trace_dispatch
                self.get_time = _get_time_resource
            elif hasattr(time, 'clock'):
                self.timer = self.get_time = time.clock
                self.dispatcher = self.trace_dispatch_i
            elif hasattr(os, 'times'):
                self.timer = os.times
                self.dispatcher = self.trace_dispatch
                self.get_time = _get_time_times
            else:
                self.timer = self.get_time = time.time
                self.dispatcher = self.trace_dispatch_i
        else:
            self.timer = timer
            t = self.timer() # test out timer function
            try:
                length = len(t)
            except TypeError:
                self.get_time = timer
                self.dispatcher = self.trace_dispatch_i
            else:
                if length == 2:
                    self.dispatcher = self.trace_dispatch
                else:
                    self.dispatcher = self.trace_dispatch_l
                # This get_time() implementation needs to be defined
                # here to capture the passed-in timer in the parameter
                # list (for performance).  Note that we can't assume
                # the timer() result contains two values in all
                # cases.
                def get_time_timer(timer=timer, sum=sum):
                    return sum(timer())
                self.get_time = get_time_timer
        self.t = self.get_time()
        self.simulate_call('profiler')

    # Heavily optimized dispatch routine for os.times() timer 
Example 78
Project: Computable   Author: ktraunmueller   File: profile.py    MIT License 4 votes vote down vote up
def __init__(self, timer=None, bias=None):
        self.timings = {}
        self.cur = None
        self.cmd = ""
        self.c_func_name = ""

        if bias is None:
            bias = self.bias
        self.bias = bias     # Materialize in local dict for lookup speed.

        if not timer:
            if _has_res:
                self.timer = resgetrusage
                self.dispatcher = self.trace_dispatch
                self.get_time = _get_time_resource
            elif hasattr(time, 'clock'):
                self.timer = self.get_time = time.clock
                self.dispatcher = self.trace_dispatch_i
            elif hasattr(os, 'times'):
                self.timer = os.times
                self.dispatcher = self.trace_dispatch
                self.get_time = _get_time_times
            else:
                self.timer = self.get_time = time.time
                self.dispatcher = self.trace_dispatch_i
        else:
            self.timer = timer
            t = self.timer() # test out timer function
            try:
                length = len(t)
            except TypeError:
                self.get_time = timer
                self.dispatcher = self.trace_dispatch_i
            else:
                if length == 2:
                    self.dispatcher = self.trace_dispatch
                else:
                    self.dispatcher = self.trace_dispatch_l
                # This get_time() implementation needs to be defined
                # here to capture the passed-in timer in the parameter
                # list (for performance).  Note that we can't assume
                # the timer() result contains two values in all
                # cases.
                def get_time_timer(timer=timer, sum=sum):
                    return sum(timer())
                self.get_time = get_time_timer
        self.t = self.get_time()
        self.simulate_call('profiler')

    # Heavily optimized dispatch routine for os.times() timer 
Example 79
Project: oss-ftp   Author: aliyun   File: profile.py    MIT License 4 votes vote down vote up
def __init__(self, timer=None, bias=None):
        self.timings = {}
        self.cur = None
        self.cmd = ""
        self.c_func_name = ""

        if bias is None:
            bias = self.bias
        self.bias = bias     # Materialize in local dict for lookup speed.

        if not timer:
            if _has_res:
                self.timer = resgetrusage
                self.dispatcher = self.trace_dispatch
                self.get_time = _get_time_resource
            elif hasattr(time, 'clock'):
                self.timer = self.get_time = time.clock
                self.dispatcher = self.trace_dispatch_i
            elif hasattr(os, 'times'):
                self.timer = os.times
                self.dispatcher = self.trace_dispatch
                self.get_time = _get_time_times
            else:
                self.timer = self.get_time = time.time
                self.dispatcher = self.trace_dispatch_i
        else:
            self.timer = timer
            t = self.timer() # test out timer function
            try:
                length = len(t)
            except TypeError:
                self.get_time = timer
                self.dispatcher = self.trace_dispatch_i
            else:
                if length == 2:
                    self.dispatcher = self.trace_dispatch
                else:
                    self.dispatcher = self.trace_dispatch_l
                # This get_time() implementation needs to be defined
                # here to capture the passed-in timer in the parameter
                # list (for performance).  Note that we can't assume
                # the timer() result contains two values in all
                # cases.
                def get_time_timer(timer=timer, sum=sum):
                    return sum(timer())
                self.get_time = get_time_timer
        self.t = self.get_time()
        self.simulate_call('profiler')

    # Heavily optimized dispatch routine for os.times() timer 
Example 80
Project: eden   Author: facebookexperimental   File: run-tests.py    GNU General Public License v2.0 4 votes vote down vote up
def _writexunit(result, outf):
        # See http://llg.cubic.org/docs/junit/ for a reference.
        timesd = dict((t[0], t[3]) for t in result.times)
        doc = minidom.Document()
        s = doc.createElement("testsuite")
        s.setAttribute("name", "run-tests")
        s.setAttribute("tests", str(result.testsRun))
        s.setAttribute("errors", "0")  # TODO
        s.setAttribute("failures", str(len(result.failures)))
        s.setAttribute("skipped", str(len(result.skipped) + len(result.ignored)))
        doc.appendChild(s)
        for tc in result.successes:
            t = doc.createElement("testcase")
            t.setAttribute("name", tc.name)
            tctime = timesd.get(tc.name)
            if tctime is not None:
                t.setAttribute("time", xunit_time(tctime))
            s.appendChild(t)
        for tc, err in sorted(result.faildata.items()):
            t = doc.createElement("testcase")
            t.setAttribute("name", tc)
            tctime = timesd.get(tc)
            if tctime is not None:
                t.setAttribute("time", xunit_time(tctime))
            # createCDATASection expects a unicode or it will
            # convert using default conversion rules, which will
            # fail if string isn't ASCII.
            err = cdatasafe(err).decode("utf-8", "replace")
            cd = doc.createCDATASection(err)
            # Use 'failure' here instead of 'error' to match errors = 0,
            # failures = len(result.failures) in the testsuite element.
            failelem = doc.createElement("failure")
            failelem.setAttribute("message", "output changed")
            failelem.setAttribute("type", "output-mismatch")
            failelem.appendChild(cd)
            t.appendChild(failelem)
            s.appendChild(t)
        for tc, message in result.skipped:
            # According to the schema, 'skipped' has no attributes. So store
            # the skip message as a text node instead.
            t = doc.createElement("testcase")
            t.setAttribute("name", tc.name)
            binmessage = message.encode("utf-8")
            message = cdatasafe(binmessage).decode("utf-8", "replace")
            cd = doc.createCDATASection(message)
            skipelem = doc.createElement("skipped")
            skipelem.appendChild(cd)
            t.appendChild(skipelem)
            s.appendChild(t)
        outf.write(doc.toprettyxml(indent="  ", encoding="utf-8"))