Python os.getloadavg() Examples

The following are code examples for showing how to use os.getloadavg(). 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: pnp   Author: HazardDede   File: monitor.py    MIT License 6 votes vote down vote up
def poll(self):
        l1m, l5m, l15m = os.getloadavg()
        uvolt, fcap, throttled, temp_limit = self._throttled()
        return {
            'cpu_count': psutil.cpu_count(),
            'cpu_freq': self._cpu_freq(),
            'cpu_temp': self._cpu_temp(),
            'cpu_use': psutil.cpu_percent(),
            'disk_use': self._disk_usage(),
            'load_1m': l1m,
            'load_5m': l5m,
            'load_15m': l15m,
            'memory_use': psutil.virtual_memory().percent,
            'rpi_cpu_freq_capped': fcap,
            'rpi_temp_limit_throttle': temp_limit,
            'rpi_throttle': throttled,
            'rpi_under_voltage': uvolt,
            'swap_use': psutil.swap_memory().percent
        } 
Example 2
Project: NiujiaoDebugger   Author: MrSrc   File: main.py    GNU General Public License v3.0 6 votes vote down vote up
def display_progress(self, test_index, test):
        if self.ns.quiet:
            return

        # "[ 51/405/1] test_tcl passed"
        line = f"{test_index:{self.test_count_width}}{self.test_count}"
        fails = len(self.bad) + len(self.environment_changed)
        if fails and not self.ns.pgo:
            line = f"{line}/{fails}"
        line = f"[{line}] {test}"

        # add the system load prefix: "load avg: 1.80 "
        if hasattr(os, 'getloadavg'):
            load_avg_1min = os.getloadavg()[0]
            line = f"load avg: {load_avg_1min:.2f} {line}"

        # add the timestamp prefix:  "0:01:05 "
        test_time = time.monotonic() - self.start_time
        test_time = datetime.timedelta(seconds=int(test_time))
        line = f"{test_time} {line}"
        print(line, flush=True) 
Example 3
Project: ironpython2   Author: IronLanguages   File: regrtest.py    Apache License 2.0 6 votes vote down vote up
def display_progress(test_index, test):
        # "[ 51/405/1] test_tcl"
        line = "{1:{0}}{2}".format(test_count_width, test_index, test_count)
        fails = len(bad) + len(environment_changed)
        if fails and not pgo:
            line = '{}/{}'.format(line, fails)
        line = '[{}]'.format(line)

        # add the system load prefix: "load avg: 1.80 "
        if hasattr(os, 'getloadavg'):
            load_avg_1min = os.getloadavg()[0]
            line = "load avg: {:.2f} {}".format(load_avg_1min, line)

        # add the timestamp prefix:  "0:01:05 "
        test_time = time.time() - regrtest_start_time
        test_time = datetime.timedelta(seconds=int(test_time))
        line = "%s %s" % (test_time, line)

        # add the test name
        line = "{} {}".format(line, test)

        print(line)
        sys.stdout.flush()

    # For a partial run, we do not need to clutter the output. 
Example 4
Project: datadog-unix-agent   Author: DataDog   File: load.py    Apache License 2.0 6 votes vote down vote up
def check(self, instance):
        try:
            load = os.getloadavg()  # os.getloadvg() not available on AIX fallback to uptime report
        except AttributeError:
            # sample output: '10:50AM   up 8 days,   2:48,  2 users,  load average: 1.19, 0.77, 0.85'
            load, _, _ = get_subprocess_output(["uptime"], self.log)
            load = load.strip().split(' ')
            load = [float(load[-3].strip(',')),
                    float(load[-2].strip(',')),
                    float(load[-1].strip(','))]

        self.gauge('system.load.1', load[0])
        self.gauge('system.load.5', load[1])
        self.gauge('system.load.15', load[2])

        # Normalize load by number of cores
        cores = psutil.cpu_count()
        assert cores >= 1, "Cannot determine number of cores"

        self.gauge('system.load.norm.1', load[0]/cores)
        self.gauge('system.load.norm.5', load[1]/cores)
        self.gauge('system.load.norm.15', load[2]/cores) 
Example 5
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: main.py    GNU General Public License v2.0 6 votes vote down vote up
def display_progress(self, test_index, text):
        if self.ns.quiet:
            return

        # "[ 51/405/1] test_tcl passed"
        line = f"{test_index:{self.test_count_width}}{self.test_count}"
        fails = len(self.bad) + len(self.environment_changed)
        if fails and not self.ns.pgo:
            line = f"{line}/{fails}"
        line = f"[{line}] {text}"

        # add the system load prefix: "load avg: 1.80 "
        load_avg = self.getloadavg()
        if load_avg is not None:
            line = f"load avg: {load_avg:.2f} {line}"

        # add the timestamp prefix:  "0:01:05 "
        test_time = time.monotonic() - self.start_time
        test_time = datetime.timedelta(seconds=int(test_time))
        line = f"{test_time} {line}"
        print(line, flush=True) 
Example 6
Project: PUSH_Clients   Author: NodePing   File: load.py    MIT License 6 votes vote down vote up
def main(system, logger):
    """
    Gets the system load average for the last 1, 5, and 15 minutes (Linux and
    FreeBSD). Gets the current CPU usage (Windows).
    """
    result = collections.OrderedDict()

    if system == 'Windows':
        import psutil

        as_percent = psutil.cpu_percent(interval=0.1)
        as_decimal = _utils.percent_to_decimal(as_percent)
        result.update({'usage': as_decimal})

    else:  # `system in ('FreeBSD', 'Linux')`
        for (key, val) in zip(('1min', '5min', '15min'), os.getloadavg()):
            result.update({key: val})

    return result 
Example 7
Project: PUSH_Clients   Author: NodePing   File: load.py    MIT License 6 votes vote down vote up
def main(system, logger):
    """
    Gets the system load average for the last 1, 5, and 15 minutes (Linux and
    FreeBSD). Gets the current CPU usage (Windows).
    """
    result = collections.OrderedDict()

    if system == 'Windows':
        import psutil

        as_percent = psutil.cpu_percent(interval=0.1)
        as_decimal = _utils.percent_to_decimal(as_percent)
        result.update({'usage': as_decimal})

    else:  # `system in ('FreeBSD', 'Linux')`
        for (key, val) in zip(('1min', '5min', '15min'), os.getloadavg()):
            result.update({key: val})

    return result 
Example 8
Project: progressivis   Author: jdfekete   File: tracer.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def end_run(self,ts,run_number,**kwds):
        if self.last_run_start is None:
            return
        row = self.last_run_start
        row['end'] = ts
        row['duration'] = ts - row['start']
        row['detail'] = self.last_run_details if self.last_run_details else ''
        row['steps'] = self.step_count
        row['loadavg'] = os.getloadavg()[0]
        row['type'] = 'run'
        row['progress_current'] = kwds.get('progress_current', 0.0)
        row['progress_max'] = kwds.get('progress_max', 0.0)
        row['quality'] = kwds.get('quality', 0.0)
        self.table.add(row)
        self.last_run_details = ''
        self.last_run_start = None 
Example 9
Project: progressivis   Author: jdfekete   File: tracer.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def after_run_step(self,ts,run_number,**kwds):
        row = self.last_run_step_start
        last_run_start = self.last_run_start
        for (name, dflt) in TableTracer.TRACER_INIT.items():
            if name not in row:
                row[name] = kwds.get(name, dflt)
        row['end'] = ts
        row['duration'] = ts - row['start']
        row['detail'] = self.last_run_step_details if self.last_run_step_details else ''
        #last_run_start['reads'] += row['reads']
        #last_run_start['updates'] += row['updates']
        #last_run_start['creates'] += row['creates']
        last_run_start['steps_run'] += row['steps_run']
        if 'debug' in kwds:
            row['type'] = 'debug_step'
        else:
            row['type'] = 'step'
        row['loadavg'] = os.getloadavg()[0]
        self.table.add(row)
        self.step_count += 1
        self.last_run_details = ''
        self.last_run_step_start = None 
Example 10
Project: Celestix-Scorpio-X-LCD   Author: camerongray1515   File: lcd.py    MIT License 6 votes vote down vote up
def disp_system_health():
    while True:
        lcd_clear()
        la = os.getloadavg()
        top_line = "CPU Load: {0} {1} {2}".format(la[0], la[1], la[2])

        with open("/sys/class/thermal/thermal_zone0/temp") as temp_f:
            temp = round(int(temp_f.read()) / 1000.0, 1)

        with open("/sys/devices/platform/w83627ehf.656/hwmon/hwmon2/device"
            "/pwm2") as pwm_f:
            fan = round(((float(pwm_f.read()) - 70.0) / 255.0) * 100, 1)

        bottom_line = "Temp: {0}c, Fan: {1}%".format(temp, fan)

        lcd_display(top_line, line=1)
        lcd_display(bottom_line, line=2)
        time.sleep(5) 
Example 11
Project: goeffel   Author: jgehrcke   File: goeffel.py    MIT License 6 votes vote down vote up
def _expensive_snapshot(self):
        # Get momentary snapshot of the TCP/UDP sockets used by the
        # process. This is a relatively costly operation, taking more
        # than 1/100 of a second:
        #
        #    timeit('p.connections()', number=100, globals=globals()) / 100
        #    0.020052049085497858
        #
        # `'inet'` means: get all TCP or UDP sockets of type IPv4 and
        # IPv6.
        ip_sockets = self._process.connections(kind='inet')

        # What follows is the acquisition of system-wide metrics.
        # https://serverfault.com/a/85481/121951
        system_mem = psutil.virtual_memory()
        loadavg = os.getloadavg()
        return ip_sockets, system_mem, loadavg 
Example 12
Project: opsbro   Author: naparuba   File: collector_loadaverage.py    MIT License 6 votes vote down vote up
def launch(self):
        self.logger.debug('getLoadAvrgs: start')
        
        # Get the triplet from the python function
        try:
            loadAvrgs_1, loadAvrgs_5, loadAvrgs_15 = os.getloadavg()
        except (AttributeError, OSError):
            self.set_not_eligible('Load average is only availabe on unix systems')
            return False
        
        self.logger.debug('getLoadAvrgs: parsing')
        
        loadavrgs = {'load1': loadAvrgs_1, 'load5': loadAvrgs_5, 'load15': loadAvrgs_15}
        
        self.logger.debug('getLoadAvrgs: completed, returning')
        
        return loadavrgs 
Example 13
Project: illuminati   Author: cloudsurf-digital   File: SystemMetric.py    MIT License 6 votes vote down vote up
def values(self):
        try:
            loadavg1, loadavg5, loadavg15 = os.getloadavg()
        except OSError:
            loadavg1, loadavg5, loadavg15 = 0, 0, 0

        try:
            phys = psutil.virtual_memory()
            swap = psutil.swap_memory()
            return {'results': {
                    'physical': (phys.percent, 'Percent'),
                    'swap': (swap.percent, 'Percent'),
                    'loadavg1': (loadavg1, 'Count'),
                    'loadavg5': (loadavg5, 'Count'),
                    'loadavg15': (loadavg15, 'Count'),
                }
            }
        except OSError as e:
            raise MetricException(e)
        except psutil.AccessDenied as e:
            raise MetricException('Access denied in psutil') 
Example 14
Project: alphacsc   Author: alphacsc   File: util.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def idle_cpu_count(mincpu=1):
    """Estimate number of idle CPUs, for use by multiprocessing code
    needing to determine how many processes can be run without excessive
    load. This function uses :func:`os.getloadavg` which is only available
    under a Unix OS.

    Parameters
    ----------
    mincpu : int
      Minimum number of CPUs to report, independent of actual estimate

    Returns
    -------
    idle : int
      Estimate of number of idle CPUs
    """

    if PY2:
        ncpu = mp.cpu_count()
    else:
        ncpu = os.cpu_count()
    idle = int(ncpu - np.floor(os.getloadavg()[0]))
    return max(mincpu, idle) 
Example 15
Project: cells   Author: AlesTsurko   File: main.py    MIT License 6 votes vote down vote up
def display_progress(self, test_index, text):
        if self.ns.quiet:
            return

        # "[ 51/405/1] test_tcl passed"
        line = f"{test_index:{self.test_count_width}}{self.test_count}"
        fails = len(self.bad) + len(self.environment_changed)
        if fails and not self.ns.pgo:
            line = f"{line}/{fails}"
        line = f"[{line}] {text}"

        # add the system load prefix: "load avg: 1.80 "
        load_avg = self.getloadavg()
        if load_avg is not None:
            line = f"load avg: {load_avg:.2f} {line}"

        # add the timestamp prefix:  "0:01:05 "
        test_time = time.monotonic() - self.start_time
        test_time = datetime.timedelta(seconds=int(test_time))
        line = f"{test_time} {line}"
        print(line, flush=True) 
Example 16
Project: sporco   Author: bwohlberg   File: util.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def idle_cpu_count(mincpu=1):
    """Estimate number of idle CPUs.

    Estimate number of idle CPUs, for use by multiprocessing code
    needing to determine how many processes can be run without excessive
    load. This function uses :func:`os.getloadavg` which is only available
    under a Unix OS.

    Parameters
    ----------
    mincpu : int
      Minimum number of CPUs to report, independent of actual estimate

    Returns
    -------
    idle : int
      Estimate of number of idle CPUs
    """

    if PY2:
        ncpu = mp.cpu_count()
    else:
        ncpu = os.cpu_count()
    idle = int(ncpu - np.floor(os.getloadavg()[0]))
    return max(mincpu, idle) 
Example 17
Project: Superior-Cache-ANalyzer   Author: Comcast   File: config.py    Apache License 2.0 6 votes vote down vote up
def setLoadAvg(loadavg: str) -> typing.Optional[Loadavg]:
	"""
	Sets the maximum-allowed loadavg, not to be exceeded during scan operations.

	If the system's loadavg already is at or exceeds `loadavg`, this function will
	complete successfully, but will return the current system loadavg to the caller.

	If `loadavg` is an incorrectly-formatted loadavg, raises a ValueError.
	"""
	global MAX_LOADAVG

	utils.log("setLoadAvg: setting to", loadavg)

	# This is broken on Windows
	currentLoadavg = os.getloadavg()

	utils.log("setLoadAvg: current loadavg is", currentLoadavg)

	MAX_LOADAVG = Loadavg(tuple(float(x) for x in loadavg.split(', ')))
	utils.log("setLoadAvg: MAX_LOADAVG is", MAX_LOADAVG)
	for i, val in enumerate(MAX_LOADAVG):
		if val < currentLoadavg[i]:
			return currentLoadavg
	return None 
Example 18
Project: contrail-api-client   Author: Juniper   File: rules.py    Apache License 2.0 6 votes vote down vote up
def determine_job_value():
    if 'CONTRAIL_BUILD_JOBS' not in os.environ: return 1

    v = os.environ['CONTRAIL_BUILD_JOBS']
    if v == 'no': return 1

    try: return int(v)
    except: pass

    try:
        import multiprocessing
        ncpu = multiprocessing.cpu_count()
        ncore = old_div(ncpu, 2)
    except:
        ncore = 1

    (one,five,_) = os.getloadavg()
    avg_load = int(one + old_div(five, 2))
    avail = old_div((ncore - avg_load) * 3, 2)
    print("scons: available jobs = %d" % avail)
    return avail 
Example 19
Project: Old-school-processing   Author: cianfrocco-lab   File: spyder.py    MIT License 5 votes vote down vote up
def toSpider(self, *args):
		" each item is a line sent to Spider"
		loadavg = os.getloadavg()[0]
		if loadavg > 2.0:
			sys.stderr.write("Load average is high "+str(round(loadavg,2))+"\n")
			loadcubed = loadavg*loadavg*loadavg
			time.sleep(loadcubed)
		sys.stderr.write("\033[35m"+"executing command: "+str(args)+"\033[0m\n")
		for item in args:
			self.spiderin.write(str(item) + '\n')
		self.spiderin.flush()
		self.logf.flush() 
Example 20
Project: cct   Author: awacha   File: telemetry.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self):
        vm = psutil.virtual_memory()
        sm = psutil.swap_memory()
        la = ', '.join([str(f) for f in os.getloadavg()])
        self.timestamp = time.monotonic()
        self.processname = multiprocessing.current_process().name
        self.rusage = resource.getrusage(resource.RUSAGE_SELF)
        self.inqueuelen = 0
        self.freephysmem = vm.available
        self.totalphysmem = vm.total
        self.freeswap = sm.free
        self.totalswap = sm.total
        self.loadavg = la 
Example 21
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def load_fetcher(update_rate=5):
    """ Get the load of the system and modify the relevant dictionary
    with the new load value.

    Args:
        update_rate (float): seconds to wait before fetching load value
    """
    while True:
        function_values[load_fetcher] = os.getloadavg()[0]
        time.sleep(update_rate) 
Example 22
Project: rpython-lang-scheme   Author: tomoh1r   File: test_extfunc.py    MIT License 5 votes vote down vote up
def test_os_getloadavg():
        def does_stuff():
            a, b, c = os.getloadavg()
            print a, b, c
            return a + b + c
        f = compile(does_stuff, [])
        res = f()
        assert type(res) is float and res >= 0.0 
Example 23
Project: agentless-system-crawler   Author: cloudviz   File: load_container_crawler.py    Apache License 2.0 5 votes vote down vote up
def crawl_load(self):
        load = os.getloadavg()
        feature_key = 'load'
        feature_attributes = LoadFeature(load[0], load[1], load[1])
        yield (feature_key, feature_attributes, 'load') 
Example 24
Project: agentless-system-crawler   Author: cloudviz   File: load_host_crawler.py    Apache License 2.0 5 votes vote down vote up
def crawl_load(self):
        load = os.getloadavg()
        feature_key = 'load'
        feature_attributes = LoadFeature(load[0], load[1], load[1])
        yield (feature_key, feature_attributes, 'load') 
Example 25
Project: banruo   Author: yingshang   File: sysinfo.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def load_average():
        return tuple(ceil(l * 1e2) / 1e2 for l in os.getloadavg()) 
Example 26
Project: infracheck   Author: riotkit-org   File: loadavg.py    Apache License 2.0 5 votes vote down vote up
def get_complete_avg() -> str:
        avg = os.getloadavg()
        return '{:.2f}, {:.2f}, {:.2f}'.format(avg[0], avg[1], avg[2]) 
Example 27
Project: infracheck   Author: riotkit-org   File: loadavg.py    Apache License 2.0 5 votes vote down vote up
def get_load_average(timing: str) -> float:
        if os.getenv('MOCK_LOAD_AVERAGE'):
            return float(os.getenv('MOCK_LOAD_AVERAGE'))

        if timing not in ['1', '5', '15']:
            raise Exception('Invalid argument, expected type to be: 1, 5 or 15')

        load = {'1': os.getloadavg()[0], '5': os.getloadavg()[1], '15': os.getloadavg()[2]}
        return load[timing] 
Example 28
Project: diamond-next   Author: diamond-next   File: loadavg.py    MIT License 5 votes vote down vote up
def collect(self):
        load01, load05, load15 = os.getloadavg()
        cpu_count = multiprocessing.cpu_count()

        if not str_to_bool(self.config['simple']):
            self.publish_gauge('01', load01, 2)
            self.publish_gauge('05', load05, 2)
            self.publish_gauge('15', load15, 2)
            self.publish_gauge('01_normalized', load01 / cpu_count, 2)
            self.publish_gauge('05_normalized', load05 / cpu_count, 2)
            self.publish_gauge('15_normalized', load15 / cpu_count, 2)
        else:
            self.publish_gauge('load', load01, 2)
            self.publish_gauge('load_normalized', load01 / cpu_count, 2)

        # Legacy: add process/thread counters provided by
        # /proc/loadavg (if available).
        if os.access(self.PROC_LOADAVG, os.R_OK):
            file = open(self.PROC_LOADAVG)
            for line in file:
                match = self.PROC_LOADAVG_RE.match(line)
                if match:
                    self.publish_gauge('processes_running',
                                       int(match.group(4)))
                    self.publish_gauge('processes_total', int(match.group(5)))
            file.close() 
Example 29
Project: hyperion-core   Author: hyperion-start   File: threads.py    GNU General Public License v3.0 5 votes vote down vote up
def request_stats():
        """You need to override this function in monitoring subclasses. It is called in the main monitoring thread.

        :return: Stat response
        :rtype: events.StatResponseEvent
        """

        load = os.getloadavg()[0]
        cpu = psutil.cpu_percent(0.5)
        mem = psutil.virtual_memory().percent
        stat_event = events.StatResponseEvent(load, cpu, mem, socket.gethostname())

        return stat_event 
Example 30
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: main.py    GNU General Public License v2.0 5 votes vote down vote up
def getloadavg(self):
        if self.win_load_tracker is not None:
            return self.win_load_tracker.getloadavg()

        if hasattr(os, 'getloadavg'):
            return os.getloadavg()[0]

        return None 
Example 31
Project: pgshards   Author: sasha-alias   File: pg_view.py    MIT License 5 votes vote down vote up
def _read_load_average(self):
        return self._transform_list(os.getloadavg()) 
Example 32
Project: heartbeats   Author: 510908220   File: script.py    MIT License 5 votes vote down vote up
def get_loadavg():
    loadavgs = os.getloadavg()
    return {
        'avg1': float(loadavgs[0]),
        'avg5': float(loadavgs[1]),
        'avg15': float(loadavgs[2]),
    } 
Example 33
Project: heartbeats   Author: 510908220   File: script_ex.py    MIT License 5 votes vote down vote up
def get_loadavg():
    loadavgs = os.getloadavg()
    return {
        'avg1': float(loadavgs[0]),
        'avg5': float(loadavgs[1]),
        'avg15': float(loadavgs[2]),
    } 
Example 34
Project: troup   Author: troup-system   File: system.py    Apache License 2.0 5 votes vote down vote up
def _get_system_stats_(self):
        stats = {}
        one, five, fifteen = os.getloadavg()
        stats['load'] = [one, five, fifteen]
        
        return stats 
Example 35
Project: blockchain   Author: trustlines-protocol   File: webservice.py    MIT License 5 votes vote down vote up
def get_process_summary():
    return {
        "pid": os.getpid(),
        "uid": os.getuid(),
        "gid": os.getgid(),
        "loadavg": os.getloadavg(),
    } 
Example 36
Project: honeybadger-python   Author: honeybadger-io   File: payload.py    MIT License 5 votes vote down vote up
def server_payload(config):
    payload = {
        'project_root': config.project_root,
        'environment_name': config.environment,
        'hostname': config.hostname,
        'time': datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"),
        'pid': os.getpid(),
        'stats': {}
    }

    s = psutil.virtual_memory()
    loadavg = os.getloadavg()

    free = float(s.free) / 1048576.0
    buffers = hasattr(s, 'buffers') and float(s.buffers) / 1048576.0 or 0.0
    cached = hasattr(s, 'cached') and float(s.cached) / 1048576.0 or 0.0
    total_free = free + buffers + cached


    payload['stats']['mem'] = {
        'total': float(s.total) / 1048576.0, # bytes -> megabytes
        'free': free,
        'buffers': buffers,
        'cached': cached,
        'total_free': total_free
    }

    payload['stats']['load'] = dict(zip(('one', 'five', 'fifteen'), loadavg))

    return payload 
Example 37
Project: progressivis   Author: jdfekete   File: case.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run_times(self, args, kwargs, step, i_th):
        ut, st, cut, cst, et = os.times()
        self._func(*args, **kwargs)
        ut_, st_, cut_, cst_, et_ = os.times()
        elapsed_time = et_ - et
        sys_time = st_ -st
        user_time = ut_ - ut
        ld_avg_1, ld_avg_5, ld_avg_15 = os.getloadavg()
        ## engine = create_engine('sqlite:///' + self.env.db_name, echo=True)
        ## metadata = MetaData()
        ## metadata.reflect(bind=engine)
        ## measurement_tbl = metadata.tables['measurement_tbl']
        stmt = (self.env.measurement_tbl.update().
                where(self.env.measurement_tbl.c.case_id==self._case_id).
                where(self.env.measurement_tbl.c.i_th==i_th).                
                where(self.env.measurement_tbl.c.step==step).
                values(
                    elapsed_time=elapsed_time,
                    sys_time=sys_time,
                    user_time=user_time,
                    ld_avg_1=ld_avg_1,
                    ld_avg_5=ld_avg_5,
                    ld_avg_15=ld_avg_15,
                    step_info=self.bench.step_info,
                    )
                )
        with self.env.engine.connect() as conn:
             conn.execute(stmt) 
Example 38
Project: progressivis   Author: jdfekete   File: benchmarkit.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run_times(self, args, kwargs, v, i_th):
        ut, st, cut, cst, et = os.times()    
        self._func(*args, **kwargs)
        ut_, st_, cut_, cst_, et_ = os.times()
        elapsed_time = et_ - et
        sys_time = st_ -st
        user_time = ut_ - ut
        ld_avg_1, ld_avg_5, ld_avg_15 = os.getloadavg()
        ## engine = create_engine('sqlite:///' + self.env.db_name, echo=True)
        ## metadata = MetaData()
        ## metadata.reflect(bind=engine)
        ## measurement_tbl = metadata.tables['measurement_tbl']
        ##if self.bench.input_proc.user_col == 'user_col_str'
        stmt = (self.env.measurement_tbl.update().
                where(self.env.measurement_tbl.c.case_id==self._case_id).
                where(self.env.measurement_tbl.c.i_th==i_th).                
                where(self.env.measurement_tbl.c[self.bench.input_proc.user_col]==v).
                values(
                    elapsed_time=elapsed_time,
                    sys_time=sys_time,
                    user_time=user_time,
                    ld_avg_1=ld_avg_1,
                    ld_avg_5=ld_avg_5,
                    ld_avg_15=ld_avg_15,
                    )
                )
        with self.env.engine.connect() as conn:
             conn.execute(stmt) 
Example 39
Project: orangepipc   Author: bkram   File: leddaemon.py    GNU General Public License v2.0 5 votes vote down vote up
def check_load(lock, *args):
    # Check load, and turn on red led if treshold is exceeded.
    while True:
        if os.getloadavg()[0] >= loadtreshold:
            setled(redled, 1)
        else:
            setled(redled, 0)
        time.sleep(sleeptime) 
Example 40
Project: peppy   Author: osukurikku   File: systemHelper.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def getSystemInfo():
	"""
	Get a dictionary with some system/server info

	:return: ["unix", "connectedUsers", "webServer", "cpuUsage", "totalMemory", "usedMemory", "loadAverage"]
	"""
	data = {"unix": runningUnderUnix(), "connectedUsers": len(glob.tokens.tokens), "matches": len(glob.matches.matches)}

	# General stats
	delta = time.time()-glob.startTime
	days = math.floor(delta/86400)
	delta -= days*86400

	hours = math.floor(delta/3600)
	delta -= hours*3600

	minutes = math.floor(delta/60)
	delta -= minutes*60

	seconds = math.floor(delta)

	data["uptime"] = "{}d {}h {}m {}s".format(days, hours, minutes, seconds)
	data["cpuUsage"] = psutil.cpu_percent()
	memory = psutil.virtual_memory()
	data["totalMemory"] = "{0:.2f}".format(memory.total/1074000000)
	data["usedMemory"] = "{0:.2f}".format(memory.active/1074000000)

	# Unix only stats
	if data["unix"]:
		data["loadAverage"] = os.getloadavg()
	else:
		data["loadAverage"] = (0,0,0)

	return data 
Example 41
Project: CTF_AWD_Platform   Author: xuchaoa   File: services.py    MIT License 5 votes vote down vote up
def get_load():
    """
    Get load average
    """
    try:
        data = os.getloadavg()[0]
    except Exception as err:
        data = str(err)

    return data 
Example 42
Project: Video-to-Online-Platform   Author: cap-ntu   File: monitor.py    Apache License 2.0 5 votes vote down vote up
def __queryCPUStat(self):
        """
        Query cpu stat.

        Returns:
            cpuStat (CPUStat): CPU statistics.
        """
        cpuStaticStat = self.__cachedCPUStaticStat
        loads = os.getloadavg()
        utilization = psutil.cpu_percent() / 100.
        cpuTimes = tuple(psutil.cpu_times())
        cpuTimesRatio = tuple(x / 100. for x in psutil.cpu_times_percent())
        return CPUStat(cpuStaticStat[0], cpuStaticStat[1], cpuStaticStat[2], cpuStaticStat[3],
                    loads, utilization, cpuTimes, cpuTimesRatio) 
Example 43
Project: BlendNet   Author: state-of-the-art   File: TaskExecutorBase.py    Apache License 2.0 5 votes vote down vote up
def getLoadStatus(self):
        '''Return current load average 1, 5, 15 mins'''
        load = (None, None, None)

        if hasattr(os, 'getloadavg'): # Linux, Mac
            load = os.getloadavg()

        return load 
Example 44
Project: landscape-client   Author: CanonicalLtd   File: load.py    GNU General Public License v2.0 5 votes vote down vote up
def run(self):
        self._sysinfo.add_header("System load", str(os.getloadavg()[0]))
        return succeed(None) 
Example 45
Project: landscape-client   Author: CanonicalLtd   File: loadaverage.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, interval=15, monitor_interval=60*60,
                 create_time=time.time, get_load_average=os.getloadavg):
        self._interval = interval
        self._monitor_interval = monitor_interval
        self._create_time = create_time
        self._load_averages = []
        self._get_load_average = get_load_average 
Example 46
Project: grizzly   Author: MozillaSecurity   File: status_reporter.py    Mozilla Public License 2.0 5 votes vote down vote up
def _sys_info():
        """Collect and format system information.

        Args:
            None

        Returns:
            str: System information formatted to match output from _summary()
        """
        txt = list()
        txt.append("CPU & Load : %d @ %0.1f%%" % (
            psutil.cpu_count(),
            psutil.cpu_percent(interval=StatusReporter.CPU_POLL_INTERVAL)))
        try:
            txt.append(" %s\n" % (str(os.getloadavg()),))
        except AttributeError:
            txt.append("\n")
        mem_usage = psutil.virtual_memory()
        txt.append("    Memory : ")
        if mem_usage.available < 1073741824:  # < 1GB
            txt.append("%dMB" % (mem_usage.available / 1048576,))
        else:
            txt.append("%0.1fGB" % (mem_usage.available / 1073741824.0,))
        txt.append(" of %0.1fGB free\n" % (mem_usage.total / 1073741824.0,))
        disk_usage = psutil.disk_usage("/")
        txt.append("      Disk : ")
        if disk_usage.free < 1073741824:  # < 1GB
            txt.append("%dMB" % (disk_usage.free / 1048576,))
        else:
            txt.append("%0.1fGB" % (disk_usage.free / 1073741824.0,))
        txt.append(" of %0.1fGB free" % (disk_usage.total / 1073741824.0,))
        return "".join(txt) 
Example 47
Project: antonov225   Author: luzeduardo   File: views.py    GNU General Public License v2.0 5 votes vote down vote up
def calc_proc_load():
    processor_load =  os.getloadavg()
    proc_len = len(processor_load)
    max_load = 1.5 * float(proc_len)
    pprc_max_loaded = 0
    for prc in processor_load:
        pprc_max_loaded += float(prc)
    if pprc_max_loaded > max_load:
        return pprc_max_loaded - max_load
    else:
        return 0 
Example 48
Project: antonov225   Author: luzeduardo   File: smiles.py    GNU General Public License v2.0 5 votes vote down vote up
def calc_proc_load():
    processor_load =  os.getloadavg()
    proc_len = len(processor_load)
    max_load = 1.5 * float(proc_len)
    pprc_max_loaded = 0
    for prc in processor_load:
        pprc_max_loaded += float(prc)
    print pprc_max_loaded
    if pprc_max_loaded > max_load:
        return pprc_max_loaded - max_load
    else:
        return 0 
Example 49
Project: ray   Author: ray-project   File: reporter.py    Apache License 2.0 5 votes vote down vote up
def get_load_avg(self):
        load = os.getloadavg()
        per_cpu_load = tuple((round(x / self.cpu_counts[0], 2) for x in load))
        return load, per_cpu_load 
Example 50
Project: exocortex-halo   Author: virtadpt   File: system_stats.py    GNU General Public License v3.0 5 votes vote down vote up
def sysload():
    sysload = {}
    system_load = os.getloadavg()
    sysload["one_minute"] = system_load[0]
    sysload["five_minute"] = system_load[1]
    sysload["fifteen_minute"] = system_load[2]
    return sysload

# check_sysload: Function that pulls the current system load and tests the
#   load averages to see if they're too high.  Takes seven arguments, the
#   sysload counter, the time between alerts, the value of status_polling, the
#   number of standard deviations to calculate, minimum and maximum system
#   stat queue lengths, and the name of a function to send a message with.
#   Sends a message to the user, returns an updated
#   value for sysload_counter.