def cpu_stats(self): ret = {} ret['cpu_ctx_switches'] = psutil.cpu_stats().ctx_switches ret['cpu_interrupts'] = psutil.cpu_stats().interrupts ret['cpu_soft_interrupts'] = psutil.cpu_stats().soft_interrupts ret['cpu_syscalls'] = psutil.cpu_stats().syscalls return ret
def get_stats(name, nic): global prev_recv global prev_sent global prev_read global prev_write with open('/proc/uptime', 'r') as f: uptime_seconds = float(f.readline().split()[0]) stats = {'date': datetime.datetime.now().isoformat(), 'name': name, 'cpu': psutil.cpu_percent(interval=None, percpu=True), 'cpu_count': psutil.cpu_count(), 'cpu_ctx_switches': psutil.cpu_stats().ctx_switches, 'cpu_interrupts': psutil.cpu_stats().interrupts, 'ram': psutil.virtual_memory().percent, 'ram-available': psutil.virtual_memory().available, 'ram-used': psutil.virtual_memory().used, 'swap': psutil.swap_memory().percent, 'swap-total': psutil.swap_memory().total, 'swap-used': psutil.swap_memory().used, 'disk_io_read': psutil.disk_io_counters().read_bytes, 'disk_io_write': psutil.disk_io_counters().write_bytes, 'disk_total': psutil.disk_usage('/').total, 'disk_used': psutil.disk_usage('/').used, 'uptime': uptime_seconds} nic_list = psutil.net_io_counters(pernic=True) nic = nic_list[nic] stats['packets_sent'] = [nic.packets_sent, nic.errout] stats['packets_recv'] = [nic.packets_recv, nic.errin] stats['bytes_recv'] = nic.bytes_recv stats['bytes_sent'] = nic.bytes_sent if prev_recv != -1: stats['dl_rate'] = stats['bytes_recv'] - prev_recv else: stats['dl_rate'] = 0 prev_recv = stats['bytes_recv'] if prev_sent != -1: stats['ul_rate'] = stats['bytes_sent'] - prev_sent else: stats['ul_rate'] = 0 prev_sent = stats['bytes_sent'] if prev_read != -1: stats['disk_read_rate'] = stats['disk_io_read'] - prev_read else: stats['disk_read_rate'] = 0 prev_read = stats['disk_io_read'] if prev_read != -1: stats['disk_write_rate'] = stats['disk_io_write'] - prev_write else: stats['disk_write_rate'] = 0 prev_write = stats['disk_io_write'] return stats
def test_cpu_stats(self): out = sh('/usr/bin/mpstat -a') re_pattern = "ALL\s*" for field in ("min maj mpcs mpcr dev soft dec ph cs ics bound rq " "push S3pull S3grd S0rd S1rd S2rd S3rd S4rd S5rd " "sysc").split(): re_pattern += "(?P<%s>\S+)\s+" % (field,) matchobj = re.search(re_pattern, out) self.assertIsNotNone( matchobj, "mpstat command returned unexpected output") # numbers are usually in the millions so 1000 is ok for tolerance CPU_STATS_TOLERANCE = 1000 psutil_result = psutil.cpu_stats() self.assertAlmostEqual( psutil_result.ctx_switches, int(matchobj.group("cs")), delta=CPU_STATS_TOLERANCE) self.assertAlmostEqual( psutil_result.syscalls, int(matchobj.group("sysc")), delta=CPU_STATS_TOLERANCE) self.assertAlmostEqual( psutil_result.interrupts, int(matchobj.group("dev")), delta=CPU_STATS_TOLERANCE) self.assertAlmostEqual( psutil_result.soft_interrupts, int(matchobj.group("soft")), delta=CPU_STATS_TOLERANCE)
def update(self): """Update CPU stats using the input method.""" # Reset stats self.reset() # Grab stats into self.stats """Update CPU stats using PSUtil.""" # Grab CPU stats using psutil's cpu_percent and cpu_times_percent # Get all possible values for CPU stats: user, system, idle, # nice (UNIX), iowait (Linux), irq (Linux, FreeBSD), steal (Linux 2.6.11+) # The following stats are returned by the API but not displayed in the UI: # softirq (Linux), guest (Linux 2.6.24+), guest_nice (Linux 3.2.0+) self.stats['total'], _ = cpumeter.get() cpu_times_percent = psutil.cpu_times_percent(interval=0.0) for stat in [ 'user', 'system', 'idle', 'nice', 'iowait', 'irq', 'softirq', 'steal', 'guest', 'guest_nice' ]: if hasattr(cpu_times_percent, stat): self.stats[stat] = getattr(cpu_times_percent, stat) # Additionnal CPU stats (number of events / not as a %) # ctx_switches: number of context switches (voluntary + involuntary) per second # interrupts: number of interrupts per second # soft_interrupts: number of software interrupts per second. Always set to 0 on Windows and SunOS. # syscalls: number of system calls since boot. Always set to 0 on Linux. try: cpu_stats = psutil.cpu_stats() except AttributeError: logger.error('cpu_stats only available with PSUtil 4.1and above') else: # By storing time data we enable Rx/s and Tx/s calculations in the # XML/RPC API, which would otherwise be overly difficult work # for users of the API time_since_update = getTimeSinceLastUpdate('cpu') # Previous CPU stats are stored in the cpu_stats_old variable if not hasattr(self, 'cpu_stats_old'): # First call, we init the cpu_stats_old var self.cpu_stats_old = cpu_stats else: for stat in cpu_stats._fields: if getattr(cpu_stats, stat) is not None: self.stats[stat] = getattr(cpu_stats, stat) - getattr( self.cpu_stats_old, stat) self.stats['time_since_update'] = time_since_update # Core number is needed to compute the CTX switch limit self.stats['cpucore'] = self.nb_log_core # Save stats to compute next step self.cpu_stats_old = cpu_stats # Append to average FILO self.cpu_average.append(self.stats) return self.stats
def _collect_system_info(self): 'collect cpuinfo, meminfo, mounts' log("Collecting system info") system = {} system['cpu'] = {} system['os'] = {} system['memory'] = {} system['disk'] = {} system['process'] = {} system['compiler'] = {} system['compiler']['make'] = run_cmd(['make', '--version'], env=self._env) system['compiler']['gcc'] = run_cmd(['gcc', '--version'], env=self._env) system['cpu']['information'] = get_cpu_info() system['cpu']['number'] = psutil.cpu_count() system['cpu']['times'] = psutil.cpu_times(percpu=False) system['cpu']['percent'] = psutil.cpu_times_percent(percpu=False) system['cpu']['stats'] = psutil.cpu_stats() system['cpu']['load_avg'] = psutil.getloadavg() system['os']['architecture'] = platform.architecture() system['os']['processor'] = platform.processor() system['os']['release'] = platform.release() system['os']['version'] = platform.version() system['os']['libc'] = platform.libc_ver() system['memory']['virtual'] = psutil.virtual_memory() system['memory']['swap'] = psutil.swap_memory() system['memory']['mounts'] = psutil.disk_partitions() system['disk']['usage'] = psutil.disk_usage('/') system['disk']['io'] = psutil.disk_io_counters(perdisk=False, nowrap=True) process = psutil.Process() system['process']['io'] = process.io_counters() system['process']['context_switches'] = process.num_ctx_switches() system['process']['cpu_times'] = process.cpu_times() system['process']['threads'] = process.num_threads() system['process']['cpu_percent'] = process.cpu_percent() system['process']['memory'] = process.memory_info() system['process']['memory_percent'] = process.memory_percent() # files to be uploaded and saved somewhere ''' with open('/proc/cpuinfo', 'r') as f: system['cpuinfo'] = f.read() with open('/proc/meminfo', 'r') as f: system['meminfo'] = f.read() with open('/proc/mounts', 'r') as f: system['mounts'] = f.read() ''' return system
def test_cpu_stats(self): # Tested more extensively in per-platform test modules. infos = psutil.cpu_stats() for name in infos._fields: value = getattr(infos, name) self.assertGreaterEqual(value, 0) if name in ('ctx_switches', 'interrupts'): self.assertGreater(value, 0)
def get_info(): time = datetime.datetime.fromtimestamp( psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S") mem = psutil.virtual_memory() per = psutil.cpu_percent(interval=1) count = psutil.cpu_count() freq = psutil.cpu_freq() stats = psutil.cpu_stats()
def fetchCpu(): """ fetch CPU info :return: type json """ return { 'cpu_times_user': psutil.cpu_times().user, 'cpu_times_system': psutil.cpu_times().system, 'cpu_times_idle': psutil.cpu_times().idle, 'cpu_percent': psutil.cpu_percent(), 'cpu_times_percent': psutil.cpu_times_percent(), 'cpu_stats_ctx_switches': psutil.cpu_stats().ctx_switches, 'cpu_stats_interrupts': psutil.cpu_stats().interrupts, 'cpu_stats_soft_interrupts': psutil.cpu_stats().soft_interrupts, 'cpu_stats_syscalls': psutil.cpu_stats().syscalls, 'getloadavg': psutil.getloadavg() }
def __set_data(self): # Cpu stats self.__infos.cpu_stat_ctx_switches = cpu_stats().ctx_switches self.__infos.cpu_stat_interrupts = cpu_stats().interrupts self.__infos.cpu_stat_soft_interrupts = cpu_stats().soft_interrupts self.__infos.cpu_stat_syscalls = cpu_stats().syscalls # Cpu times self.__infos.cpu_times_user = cpu_times().user self.__infos.cpu_times_system = cpu_times().system self.__infos.cpu_times_nice = cpu_times().nice self.__infos.cpu_times_softirq = cpu_times().softirq self.__infos.cpu_times_irq = cpu_times().irq self.__infos.cpu_times_iowait = cpu_times().iowait self.__infos.cpu_times_guest = cpu_times().guest self.__infos.cpu_times_guest_nice = cpu_times().guest_nice self.__infos.cpu_times_idle = cpu_times().idle
def render(draw, width, height): stats = psutil.cpu_stats() draw.text((10, 0), 'Ctx switch', fill='white', font=default) right_text(draw, width, 0, text=str(stats.ctx_switches), font=default) draw.text((10, 10), 'Interrupts', fill='white', font=default) right_text(draw, width, 10, text=str(stats.interrupts), font=default) draw.text((10, 20), 'Soft intr', fill='white', font=default) right_text(draw, width, 20, text=str(stats.soft_interrupts), font=default)
def get_cpu_stat(): cpu_stats = psutil.cpu_stats() return { 'ctx_switches': cpu_stats.ctx_switches, 'interrupts': cpu_stats.interrupts, 'soft_interrupts': cpu_stats.soft_interrupts, 'syscalls': cpu_stats.syscalls }
def get_stats(task): click.echo('getting stats %s' % task) if (task == 'cpu' or task == 'all'): cpu_stats = psutil.cpu_stats() click.echo(cpu_stats) if (task == 'disk' or task == 'all'): disk_usage = psutil.disk_usage('C:/') click.echo(disk_usage)
def cpu_stats(): stats = psutil.cpu_stats() return { 'ctx_switches': stats.ctx_switches, 'interrupts': stats.interrupts, 'soft_interrupts': stats.soft_interrupts, # always 0 on windows 'syscalls': stats.syscalls # always 0 on linux }
def test(): print('CPU逻辑数量: ', psutil.cpu_count()) print('getloadavg : ', psutil.getloadavg()) print('cpu 空闲率 : ', psutil.cpu_percent()) print('cpu 频率 : ', psutil.cpu_freq()) print('cpu 统计 : ', psutil.cpu_stats()) print('cpu times : ', psutil.cpu_times()) print('cpu times% : ', psutil.cpu_times_percent())
def get_cpu_stat_test(): print(psutil.cpu_freq()) print('\n') print(psutil.cpu_stats()) print('\n') print(psutil.cpu_times_percent(interval=1)) CPUList = psutil.cpu_times_percent(interval=1, percpu=True) for member in CPUList: print(member)
def cpu_stats(): """Get CPU stats.""" data = {} stats = psutil.cpu_stats() data["ctx_switches"] = stats.ctx_switches data["interrupts"] = stats.interrupts data["soft_interrupts"] = stats.soft_interrupts data["syscalls"] = stats.syscalls return data
def get_cpu_stat(): cpu_stats = psutil.cpu_stats() s = "---------- CPU status ----------\n" s += "* コンテキストスイッチ回数 \t" + str(cpu_stats.ctx_switches) + "\n" s += "* 割り込み回数 \t" + str(cpu_stats.interrupts) + "\n" s += "* ソフトによる割り込み回数\t" + str(cpu_stats.soft_interrupts) + "\n" s += "* システムコール回数 \t" + str(cpu_stats.syscalls) + "\n" return s
def run(self): while True: if self.enableAdaptor: print('\n---------------') print('New system performance reading:') print(' ' + str(psutil.cpu_stats())) print(' ' + str(psutil.virtual_memory())) # print(' ' + str(psutil.sensors_temperatures(False))) sleep(self.rateInSec)
def run(self): while (True): if self.enableAdaptor: print("\n---------------") print('New system performance readings:') print(' ' + str(psutil.cpu_stats())) print(' ' + str(psutil.virtual_memory())) sleep(self.rateInSec)
def cpuInfo(self): """ get CPU info :return: CPU info """ return { 'cpu_times_user': psutil.cpu_times().user, 'cpu_times_system': psutil.cpu_times().system, 'cpu_times_idle': psutil.cpu_times().idle, 'cpu_percent': psutil.cpu_percent(), 'cpu_times_percent_user': psutil.cpu_times_percent().user, 'cpu_times_percent_system': psutil.cpu_times_percent().system, 'cpu_times_percent_idle': psutil.cpu_times_percent().idle, 'cpu_stats_ctx_switches': psutil.cpu_stats().ctx_switches, 'cpu_stats_interrupts': psutil.cpu_stats().interrupts, 'cpu_stats_soft_interrupts': psutil.cpu_stats().soft_interrupts, 'cpu_stats_syscalls': psutil.cpu_stats().syscalls, }
def GetCPUStatistics(): cpustats = psutil.cpu_stats() retndata = { "ctxs": cpustats.ctx_switches, "intr": cpustats.interrupts, "soft": cpustats.soft_interrupts, "sysc": cpustats.syscalls, } return retndata
def cpu_info(): # cpu_frep = psutil.cpu_freq() cpu_per = psutil.cpu_percent() # cpu使用量 cpu_status = psutil.cpu_stats() cpu_times = psutil.cpu_times() # print('cpu_frep:', cpu_frep) print('cpu_per:', cpu_per) print('cpu_status:', cpu_status) print('cpu_times:', cpu_times)
def run(self): while True: if 1: print('\n--------------------') print('New system performance readings:') print(' ' + str(psutil.cpu_stats())) print(' ' + str(psutil.virtual_memory())) # print(' ' + str(psutil.sensors_temperatures(False))) time.sleep(5)
def get_cpu(self): cpu_dic = dict() cpu_dic['cpu_count'] = psutil.cpu_count() cpu_dic['cpu_percent'] = psutil.cpu_percent() cpu_dic['cpu_times'] = psutil.cpu_times() cpu_dic['cpu_times_percent'] = psutil.cpu_times_percent() cpu_dic['cpu_stats'] = psutil.cpu_stats() cpu_dic['cpu_freq'] = psutil.cpu_freq() return cpu_dic
def test_cpu_stats_ctx_switches(self): with open('/proc/stat', 'rb') as f: for line in f: if line.startswith(b'ctxt'): ctx_switches = int(line.split()[1]) break else: raise ValueError("couldn't find line") self.assertAlmostEqual( psutil.cpu_stats().ctx_switches, ctx_switches, delta=1000)
def health(): data = { socket.gethostname(): [{ 'RAM': psutil.virtual_memory()._asdict() }, { 'CPU': psutil.cpu_stats()._asdict() }] } response.content_type = 'application/json' return json.dumps(data, indent=4)
def test_cpu_stats_interrupts(self): with open('/proc/stat', 'rb') as f: for line in f: if line.startswith(b'intr'): interrupts = int(line.split()[1]) break else: raise ValueError("couldn't find line") self.assertAlmostEqual( psutil.cpu_stats().interrupts, interrupts, delta=1000)
def get_cpu_metrics(): """ Collects CPU metrics and returns a list of objects. """ cpu_metrics = {} cpu_metrics.update(namedtuple_to_dict(psutil.cpu_stats())) cpu_metrics.update(namedtuple_to_dict(psutil.cpu_freq())) cpu_metrics.update(namedtuple_to_dict(psutil.cpu_times())) return {'cpu': cpu_metrics}
def cpuTimes(): # CPU 的暂时用不到, 等到需要的时候再来整理 print psutil.cpu_times(percpu=False) # print psutil.cpu_percent(interval=None, percpu=False) time.sleep(0.2) print psutil.cpu_percent(interval=0.2, percpu=True) # 统计 cpu 的数量 print psutil.cpu_count() # 统计 CPU 的状态信息 print psutil.cpu_stats() # 输出 CPU的频率 print psutil.cpu_freq(percpu=False) # 输出系统的平均负载: 1 分钟, 5 分钟, 15 分钟 print psutil.getloadavg() print [x / psutil.cpu_count() * 100 for x in psutil.getloadavg()]
def check_computer_info(): print("check cpu_times") print(psutil.cpu_times()) print(psutil.cpu_percent()) print(psutil.cpu_times_percent(interval=None, percpu=False)) print(psutil.cpu_count(logical=True)) print(psutil.cpu_stats()) print(psutil.cpu_freq(percpu=False)) print(psutil.getloadavg()) print() print()
def cpu_stats(measurement): stats = psutil.cpu_stats() return [ CPUStats( measurement=measurement, ctx_switches=stats.ctx_switches, interrupts=stats.interrupts, soft_interrupts=stats.soft_interrupts, syscalls=stats.syscalls, ) ]
def processador(): inicio = time.time() lista = [] lista_med = [] info = cpuinfo.get_cpu_info() dic_cpu = [] dic_cpu = psutil.cpu_stats() dic_cpu_nucleo = [] dic_cpu_nucleo = psutil.cpu_percent(interval=1, percpu=True) lista_nucleo = [] nome_cpu = info['brand'] arq_cpu = info['arch'] palavra_cpu = str(info['bits']) freq_base = info['hz_advertised'] for i in range(10): freq_cpu = psutil.cpu_freq().current / 1000 time.sleep(1) lista_med.append(freq_cpu) freq_cpu = str(int(sum(lista_med)) / int(len(lista_med))) lista_med_uso = [] for i in range(10): uso_cpu = psutil.cpu_percent() time.sleep(1) lista_med_uso.append(uso_cpu) uso_cpu = str(int(sum(lista_med_uso)) / int(len(lista_med_uso))) lista_nucleo = psutil.cpu_percent(interval=1, percpu=True) nucleos_cpu_logicos = str(psutil.cpu_count(logical=True)) nucleos_cpu_fisicos = str(psutil.cpu_count(logical=False)) lista.append(nome_cpu) lista.append(arq_cpu) lista.append(palavra_cpu) lista.append(freq_base) lista.append(freq_cpu) lista.append(uso_cpu) lista.append(lista_nucleo) lista.append(nucleos_cpu_logicos) lista.append(nucleos_cpu_fisicos) fim = time.time() print("Tempo da chamada:", round((fim - inicio), 2), "segundo(s).") return lista
def __init__(self): self.hostname = socket.gethostname() self.iface = ni.interfaces()[1] self.ipaddr = ni.ifaddresses(self.iface)[2][0]['addr'] self.mem = psutil.virtual_memory() self.cpu_logical = psutil.cpu_count() self.cpu = psutil.cpu_count(logical=True) self.cpu_time = psutil.cpu_times() self.cpu_stats = psutil.cpu_stats() self.disk = psutil.disk_usage('/') self.users = psutil.users()
def test_cpu_stats(self): # Tested more extensively in per-platform test modules. infos = psutil.cpu_stats() self.assertEqual( infos._fields, ('ctx_switches', 'interrupts', 'soft_interrupts', 'syscalls')) for name in infos._fields: value = getattr(infos, name) self.assertGreaterEqual(value, 0) # on AIX, ctx_switches is always 0 if not AIX and name in ('ctx_switches', 'interrupts'): self.assertGreater(value, 0)
def _update_agent_system(agent): """Update agent with system data. Args: agent: Agent object uid: Unique ID for Agent config: Configuration object Returns: None """ ######################################################################### # Set non chartable values ######################################################################### agent.populate_single('release', platform.release(), base_type=None) agent.populate_single('system', platform.system(), base_type=None) agent.populate_single('version', platform.version(), base_type=None) dist = platform.linux_distribution() agent.populate_single('distribution', ' '.join(dist), base_type=None) agent.populate_single('cpu_count', psutil.cpu_count(), base_type=1) ######################################################################### # Set chartable values ######################################################################### agent.populate_single( 'process_count', len(psutil.pids()), base_type=1) agent.populate_named_tuple( psutil.cpu_times_percent(), prefix='cpu_times_percent', base_type=1) # Load averages (la_01, la_05, la_15) = os.getloadavg() agent.populate_single( 'load_average_01min', la_01, base_type=1) agent.populate_single( 'load_average_05min', la_05, base_type=1) agent.populate_single( 'load_average_15min', la_15, base_type=1) # Get CPU times agent.populate_named_tuple( psutil.cpu_times(), prefix='cpu_times', base_type=64) # Get CPU stats agent.populate_named_tuple( psutil.cpu_stats(), prefix='cpu_stats', base_type=64) # Get memory utilization agent.populate_named_tuple(psutil.virtual_memory(), prefix='memory')
def cpu_info(request): if request.method == 'GET': cpu_percent = str(psutil.cpu_percent()) cpu_stats= str(psutil.cpu_stats()) cpu_count= str(psutil.cpu_count()) cpu_info = {} cpu_info['cpu_rate']= cpu_percent cpu_info['cpu_stats']= cpu_stats cpu_info['cpu_count']= cpu_count return HttpResponse(json.dumps(cpu_info)) else: cpu_info = {} cpu_info['error']= "error" return HttpResponse(json.dumps(cpu_info))
def get_cpu_details(self): cpu_details ={ 'cpu_info':{ } } ### CPU details ### cpustat = psutil.cpu_stats() cpu_details['cpu_info']['ctx_switches'] = cpustat.ctx_switches cpu_details['cpu_info']['interrupts'] = cpustat.interrupts cpu_details['cpu_info']['soft_interrupts'] = cpustat.soft_interrupts cpu_details['cpu_info']['syscalls'] = cpustat.syscalls return cpu_details
def trun(self): global interval global snap_stap print("Writing info in txt file(SNAPSHOT #{})".format(snap_stap)) with open("monitorapp.txt", "a+") as txtfile: txtfile.write( "\nSNAPSHOT " + "%s" % snap_stap + ":" + " [%s]" % datetime.datetime.now()) txtfile.write( "\nNumber of CPUs: " +str(psutil.cpu_count())) txtfile.write( "\nNumber of Physical CPUs: " +str(psutil.cpu_count(logical=False))) txtfile.write( "\nOverall CPU load: " +str(psutil.cpu_stats())) txtfile.write( "\nOverall virtual memory usage: " +str(psutil.virtual_memory())) txtfile.write( "\nOverall swap memory usage: " +str(psutil.swap_memory())) txtfile.write( "\nIO information: " +str(psutil.disk_io_counters(perdisk=True))) txtfile.write( "\nNetwork information: " +str(psutil.net_io_counters())) txtfile.close() snap_stap += 1
def update_local(self): """Update CPU stats using psutil.""" # Grab CPU stats using psutil's cpu_percent and cpu_times_percent # Get all possible values for CPU stats: user, system, idle, # nice (UNIX), iowait (Linux), irq (Linux, FreeBSD), steal (Linux 2.6.11+) # The following stats are returned by the API but not displayed in the UI: # softirq (Linux), guest (Linux 2.6.24+), guest_nice (Linux 3.2.0+) # Init new stats stats = self.get_init_value() stats['total'] = cpu_percent.get() cpu_times_percent = psutil.cpu_times_percent(interval=0.0) for stat in ['user', 'system', 'idle', 'nice', 'iowait', 'irq', 'softirq', 'steal', 'guest', 'guest_nice']: if hasattr(cpu_times_percent, stat): stats[stat] = getattr(cpu_times_percent, stat) # Additional CPU stats (number of events not as a %; psutil>=4.1.0) # ctx_switches: number of context switches (voluntary + involuntary) per second # interrupts: number of interrupts per second # soft_interrupts: number of software interrupts per second. Always set to 0 on Windows and SunOS. # syscalls: number of system calls since boot. Always set to 0 on Linux. cpu_stats = psutil.cpu_stats() # By storing time data we enable Rx/s and Tx/s calculations in the # XML/RPC API, which would otherwise be overly difficult work # for users of the API time_since_update = getTimeSinceLastUpdate('cpu') # Previous CPU stats are stored in the cpu_stats_old variable if not hasattr(self, 'cpu_stats_old'): # First call, we init the cpu_stats_old var self.cpu_stats_old = cpu_stats else: for stat in cpu_stats._fields: if getattr(cpu_stats, stat) is not None: stats[stat] = getattr(cpu_stats, stat) - getattr(self.cpu_stats_old, stat) stats['time_since_update'] = time_since_update # Core number is needed to compute the CTX switch limit stats['cpucore'] = self.nb_log_core # Save stats to compute next step self.cpu_stats_old = cpu_stats return stats
def _poll(current, last_value): # normalize with effective period diff = 1. if self._last_period: diff = self._last_period / 10**9 # int values: bytes_sent, bytes_recv, packets_sent, packets_recv, errin, errout, dropin, dropout current['network'] = dict(psutil.net_io_counters()._asdict()) # int values: read_count, write_count, read_bytes, write_bytes, read_time, write_time, read_merged_count, write_merged_count, busy_time current['disk'] = dict(psutil.disk_io_counters()._asdict()) if last_value: for k in ['network', 'disk']: d = current[k] for k2 in list(d.keys()): value = float(d[k2] - last_value[k][k2]) / diff d['{}_per_sec'.format(k2)] = int(value) # float values: user, nice, system, idle, iowait, irq, softirq, streal, guest, guest_nice current['cp'] = dict(psutil.cpu_times_percent(interval=None)._asdict()) cpu_freq = psutil.cpu_freq() current['cp']['freq'] = round(cpu_freq.current) if cpu_freq else None s = psutil.cpu_stats() current['cp']['ctx_switches'] = s.ctx_switches current['cp']['interrupts'] = s.interrupts current['cp']['soft_interrupts'] = s.soft_interrupts # int values: total, available, used, free, active, inactive, buffers, cached, shared, slab # float values: percent current['memory'] = dict(psutil.virtual_memory()._asdict()) # Network connections res = {} conns = psutil.net_connections(kind='all') for c in conns: if c.family not in res: res[c.family] = 0 res[c.family] += 1 res2 = {} for f, cnt in res.items(): res2[f.name] = cnt current['network']['connection'] = res2 return current
def cpu_stats_info(self): ''' Note: Get stats of CPU cpu_stats_dict: :return: dict type { 'ctx_switches': value, 'interrupts': value, 'soft_interrupts': value, 'syscalls':value } ''' cpu_stats_dict = dict() cpu_stats = psutil.cpu_stats() cpu_stats_dict['ctx_switches'] = cpu_stats.ctx_switches cpu_stats_dict['interrupts'] = cpu_stats.interrupts cpu_stats_dict['soft_interrupts'] = cpu_stats.soft_interrupts cpu_stats_dict['syscalls'] = cpu_stats.syscalls return cpu_stats_dict
def get_status(): t0 = time.time() ret = dict() def percent(ret): ret["cpupercent"] = psutil.cpu_percent(interval=0.49, percpu=True) def times(ret): cputimes = psutil.cpu_times_percent(interval=0.49, percpu=True) ret["cputimes"] = [] for i in cputimes: ret["cputimes"].append(obj2dict(i)) threads = [] threads.append(threading.Thread(target=percent, daemon=True, args=(ret,))) threads.append(threading.Thread(target=times, daemon=True, args=(ret,))) for i in threads: i.start() i.join() ret["status"] = obj2dict(psutil.cpu_stats()) return ret
def jrun(self): global interval global snap_stap print "Writing info in json file(SNAPSHOT #{})".format(snap_stap) with open("monitorapp.json", "a+") as jsonfile: jsonfile.write("\nSNAPSHOT " + "%s" % snap_stap + ":" + " [%s]" % datetime.datetime.now()) jsonfile.write("\nNumber of CPUs\n") json.dump((psutil.cpu_count()), jsonfile, indent=4) jsonfile.write("\nNumber of Physical CPUs\n") json.dump((psutil.cpu_count(logical=False)), jsonfile, indent=4) jsonfile.write("\nOverall CPU load\n") json.dump(super(jcreate, self).creates_dict(psutil.cpu_stats()), jsonfile, indent=4) jsonfile.write("\nOverall virtual memory usage\n") json.dump(super(jcreate, self).creates_dict(psutil.virtual_memory()), jsonfile, indent=4) jsonfile.write("\nOverall swap memory usage\n") json.dump(super(jcreate, self).creates_dict(psutil.swap_memory()), jsonfile, indent=4) jsonfile.write("\nIO information\n") json.dump((psutil.disk_io_counters(perdisk=True)), jsonfile, indent=4) jsonfile.write("\nNetwork information\n") json.dump(super(jcreate, self).creates_dict(psutil.net_io_counters()), jsonfile, indent=4) jsonfile.write("\n\n") jsonfile.close() snap_stap += 1
def getSystemInfo(cls): system = { 'boot_time': psutil.boot_time(), 'cpu_count': psutil.cpu_count(), 'cpu_stats': psutil.cpu_stats().__dict__, 'cpu_times': [k.__dict__ for k in psutil.cpu_times(percpu=True)], 'disk_io_counters': psutil.disk_io_counters().__dict__, 'disk_usage': [], 'net_io_counters': psutil.net_io_counters().__dict__, 'swap_memory': psutil.swap_memory().__dict__, 'virtual_memory': psutil.virtual_memory().__dict__ } partitions = psutil.disk_partitions() for p in partitions: if p.mountpoint in cls.INCLUDED_PARTITIONS: usage = psutil.disk_usage(p.mountpoint) system['disk_usage'].append({ 'mountpoint': p.mountpoint, 'total': usage.total, 'used': usage.used }) return system
def interrupts_count(): count = psutil.cpu_stats().interrupts return count
import mysql.connector import datetime ## set globals computerName = 'Williams-Lab' cnx = mysql.connector.connect(host="104.154.235.236", user="******", password='******', dbname="timeSDM") cursor = cnx.cursor(buffered=True) print "Time\tAverageCPU\tUsed Memory\tAvailable Memory\tNum Procs\tSeconds Since Boot\t\n" while True: cpuCount = psutil.cpu_count() cpuUsage = psutil.cpu_percent(percpu=True) cpuAvg = psutil.cpu_percent() cpuStats = psutil.cpu_stats() try: cpu1 = cpuUsage[0] except: cpu1 = None try: cpu2 = cpuUsage[1] except: cpu2 = None try: cpu3 = cpuUsage[2] except: cpu3 = None try: cpu4 = cpuUsage[3] except:
def ctx_switches(): count = psutil.cpu_stats().ctx_switches return count
def stats(): return psutil.cpu_stats()
def test_cpu_stats_syscalls(self): self.assertAlmostEqual(psutil.cpu_stats().syscalls, sysctl('vm.stats.sys.v_syscall'), delta=1000)
def test_cpu_stats_soft_interrupts(self): self.assertAlmostEqual(psutil.cpu_stats().soft_interrupts, sysctl('vm.stats.sys.v_soft'), delta=1000)
def test_cpu_stats_ctx_switches(self): self.assertAlmostEqual(psutil.cpu_stats().ctx_switches, sysctl('vm.stats.sys.v_swtch'), delta=1000)
def test_cpu_stats_traps(self): self.assertAlmostEqual(psutil.cpu_stats().traps, sysctl('vm.stats.sys.v_trap'), delta=1000)
def CPU_Stats(): try: print(psutil.cpu_stats()) except Exception(): print(Exception)
def cpu_stats(): return {'cpu_stats': psutil.cpu_stats()}
from psutil import cpu_times, cpu_stats, virtual_memory x = cpu_times() print 'cpu_times()' print x print ' ' #access of namedtuple attibutes print 'user: {0}'.format(x.user) print 'system: {0}'.format(x.system) print 'idle: {0}'.format(x.idle) print 'interrupt: {0}'.format(x.interrupt) print 'dpc: {0}'.format(x.dpc) print ' ' c = cpu_stats() print 'cpu_stats()' print c print ' ' m = virtual_memory() print 'virtual_memory(): ' print m print ' '
#!/usr/bin/env python import psutil print psutil.cpu_times() print "psutil.cpu_count is :", psutil.cpu_count() print "psutil.cpu_times(percpu=True)",psutil.cpu_times(percpu=True) for x in range(psutil.cpu_count()): print psutil.cpu_percent(interval=1,percpu=True) print "psutil.cpu_stats",psutil.cpu_stats() for x in range(4): print psutil.cpu_percent(interval=1,percpu=True) print "virtual_memory is",psutil.virtual_memory() print "swap_memory is ",psutil.swap_memory() print "psutil.user is ",psutil.users() print "psutil.disk_partitions is ",psutil.disk_partitions() for x in (psutil.disk_partitions()): print x print psutil.disk_usage('c:\\') print psutil.disk_io_counters(perdisk=True) print 'net_io_counters',psutil.net_io_counters(pernic=False)