Python os.times() Examples

The following are 30 code examples of os.times(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module os , or try the search function .
Example #1
Source File: file_codec.py    From compare-codecs with Apache License 2.0 6 votes vote down vote up
def _EncodeFile(self, parameters, bitrate, videofile, encodedfile):
    commandline = self.EncodeCommandLine(
      parameters, bitrate, videofile, encodedfile)

    print commandline
    with open(os.path.devnull, 'r') as nullinput:
      times_start = os.times()
      returncode = subprocess.call(commandline, shell=True, stdin=nullinput)
      times_end = os.times()
      subprocess_cpu = times_end[2] - times_start[2]
      elapsed_clock = times_end[4] - times_start[4]
      print "Encode took %f CPU seconds %f clock seconds" % (
          subprocess_cpu, elapsed_clock)
      if returncode:
        raise Exception("Encode failed with returncode %d" % returncode)
      return (subprocess_cpu, elapsed_clock) 
Example #2
Source File: session.py    From mishkal with GNU General Public License v3.0 6 votes vote down vote up
def unique_id(self, for_object=None):
        """
        Generates an opaque, identifier string that is practically
        guaranteed to be unique.  If an object is passed, then its
        id() is incorporated into the generation.  Relies on md5 and
        returns a 32 character long string.
        """
        r = [time.time(), random.random()]
        if hasattr(os, 'times'):
            r.append(os.times())
        if for_object is not None:
            r.append(id(for_object))
        md5_hash = md5(str(r))
        try:
            return md5_hash.hexdigest()
        except AttributeError:
            # Older versions of Python didn't have hexdigest, so we'll
            # do it manually
            hexdigest = []
            for char in md5_hash.digest():
                hexdigest.append('%02x' % ord(char))
            return ''.join(hexdigest) 
Example #3
Source File: jsdir_linux.py    From Jsdir with 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 #4
Source File: __init__.py    From Galaxy_Plugin_Bethesda with 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 #5
Source File: __init__.py    From vnpy_crypto with 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 #6
Source File: test_process.py    From vnpy_crypto with 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 #7
Source File: __init__.py    From psutil with BSD 3-Clause "New" or "Revised" 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
Source File: __init__.py    From NoobSec-Toolkit with GNU General Public License v2.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 #9
Source File: __init__.py    From NoobSec-Toolkit with GNU General Public License v2.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 #10
Source File: __init__.py    From teleport with 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 #11
Source File: __init__.py    From teleport with 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
Source File: __init__.py    From teleport with 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 #13
Source File: __init__.py    From Galaxy_Plugin_Bethesda with 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 #14
Source File: frontend.py    From python-docs-samples with Apache License 2.0 5 votes vote down vote up
def get_user_cputime(self):
        return os.times()[0] 
Example #15
Source File: __init__.py    From Galaxy_Plugin_Bethesda with 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 macOS and Windows children_user and children_system are
        always set to 0.
        """
        return self._proc.cpu_times() 
Example #16
Source File: __init__.py    From NoobSec-Toolkit with GNU General Public License v2.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 #17
Source File: experiment.py    From cgat-core with MIT License 5 votes vote down vote up
def get_footer():
    """return a header string with command line options and
    timestamp.
    """
    return "job finished in %i seconds at %s -- %s -- %s" %\
           (time.time() - global_starting_time,
            time.asctime(time.localtime(time.time())),
            " ".join(["%5.2f" % x for x in os.times()[:4]]),
            global_id) 
Example #18
Source File: __init__.py    From NoobSec-Toolkit with GNU General Public License v2.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 #19
Source File: __init__.py    From NoobSec-Toolkit with GNU General Public License v2.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
Source File: profile.py    From Fluid-Designer with 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 #21
Source File: __init__.py    From script-languages with MIT License 5 votes vote down vote up
def os_timer():
    before = os.times()
    try:
        yield
    finally:
        after = os.times()
        print '\nreal %7.2fs\nuser %7.2fs\nsys  %7.2fs\n' % (
            after[4] - before[4], after[0] - before[0], after[1] - before[1]) 
Example #22
Source File: __init__.py    From teleport with 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 #23
Source File: profile.py    From datafari with 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 #24
Source File: __init__.py    From teleport with 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 #25
Source File: fakesession.py    From ipmisim with Apache License 2.0 5 votes vote down vote up
def _monotonic_time():
    return os.times()[4] 
Example #26
Source File: __init__.py    From teleport with 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 #27
Source File: __init__.py    From teleport with 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 #28
Source File: __init__.py    From teleport with 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 #29
Source File: scheduler.py    From UIP with GNU Affero General Public License v3.0 5 votes vote down vote up
def changeCycle(self):
        """Wallpaper change cycle."""
        uold, sold, cold, c, e = os.times()
        while True:
            delta = self.deltaTime()
            if delta >= self.timeout:
                self.change_next()
                self.time = time.time()
            unew, snew, cnew, c, e = os.times()
            start = time.time()
            percentage = get_percentage(unew, uold, start)
            if percentage > 30.0:
                time.sleep(0.1) 
Example #30
Source File: __init__.py    From NoobSec-Toolkit with GNU General Public License v2.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()