本文整理汇总了Python中psutil.virtual_memory函数的典型用法代码示例。如果您正苦于以下问题:Python virtual_memory函数的具体用法?Python virtual_memory怎么用?Python virtual_memory使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了virtual_memory函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: meminfo
def meminfo():
mem = int((psutil.virtual_memory().active/psutil.virtual_memory().total)*100)
if mem >= 90:
return ("MEM: {0}%".format(mem), RED)
elif mem <= 10:
return ("MEM: {0}%".format(mem), BLUE)
else:
return ("MEM: {0}%".format(mem), GREEN)
示例2: cpustat
def cpustat(self):
tags="node:%s %s"%(self.nodename,self.tags)
val=int(psutil.cpu_percent())
measurement="cpu_perc"
key="%s.%s"%(self.nodename,measurement)
self.measure(key,measurement,tags,val,aggrkey=measurement)
val=int(psutil.virtual_memory()[1]/1024/1024)
measurement="mem_free_mb"
key="%s.%s"%(self.nodename,measurement)
self.measure(key,measurement,tags,val,aggrkey=measurement)
val=int(psutil.swap_memory()[3])
measurement="mem_virt_perc"
key="%s.%s"%(self.nodename,measurement)
self.measure(key,measurement,tags,val,aggrkey=measurement)
val=int(psutil.virtual_memory()[2])
measurement="mem_phy_perc"
key="%s.%s"%(self.nodename,measurement)
self.measure(key,measurement,tags,val,aggrkey=measurement)
res=psutil.cpu_times_percent()
names=["cputimeperc_user","cputimeperc_nice","cputimeperc_system","cputimeperc_idle","cputimeperc_iowait","cputimeperc_irq","cputimeperc_softirq","steal","guest","guest_nice"]
for i in range(len(names)):
if names[i].startswith("cputime"):
val=int(res[i])
measurement=names[i]
key="%s.%s"%(self.nodename,measurement)
self.measure(key,measurement,tags,val,aggrkey=measurement)
示例3: sysinfo
def sysinfo():
boot_start = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(psutil.boot_time()))
time.sleep(0.5)
cpu_usage = psutil.cpu_percent()
ram = int(psutil.virtual_memory().total / (1027 * 1024))
ram_percent = psutil.virtual_memory().percent
swap = int(psutil.swap_memory().total / (1027 * 1024))
swap_percent = psutil.swap_memory().percent
net_sent = psutil.net_io_counters().bytes_sent
net_recv = psutil.net_io_counters().bytes_recv
net_spkg = psutil.net_io_counters().packets_sent
net_rpkg = psutil.net_io_counters().packets_recv
sysinfo_string = ""
if __name__ == "__main__":
bfh = r'%'
print(" \033[1;32m开机时间:%s\033[1;m" % boot_start)
print(" \033[1;32m当前CPU使用率:%s%s\033[1;m" % (cpu_usage, bfh))
print(" \033[1;32m物理内存:%dM\t使用率:%s%s\033[1;m" % (ram, ram_percent, bfh))
print(" \033[1;32mSwap内存:%dM\t使用率:%s%s\033[1;m" % (swap, swap_percent, bfh))
print(" \033[1;32m发送:%d Byte\t发送包数:%d个\033[1;m" % (net_sent, net_spkg))
print(" \033[1;32m接收:%d Byte\t接收包数:%d个\033[1;m" % (net_recv, net_rpkg))
for i in psutil.disk_partitions():
print(" \033[1;32m盘符: %s 挂载点: %s 使用率: %s%s\033[1;m" % (i[0], i[1], psutil.disk_usage(i[1])[3], bfh))
sysinfo_string = '开机时间: ' + boot_start + '\n'
sysinfo_string += '当前CPU使用率: ' + str(cpu_usage) + '%\n'
sysinfo_string += '物理内存: ' + str(ram) + 'M\t使用率: ' + str(ram_percent) + '%\t'
sysinfo_string += 'Swap内存: ' + str(swap) + 'M\t使用率: ' + str(swap_percent) + '%\n'
return sysinfo_string
else:
file = open("sysinfo.log", "a")
file.write("CPU:%s \tRAM:%s\tnet_recv:%d\tNet_sent:%d\r\n" % (cpu_usage, ram_percent, net_recv, net_sent))
file.flush()
file.close()
示例4: Sysinfo
def Sysinfo():
Hostname = platform.node()
Sys_version = platform.platform()
Boot_Start = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(psutil.boot_time()))
time.sleep(0.5)
Cpu_usage = psutil.cpu_percent()
RAM = int(psutil.virtual_memory().total/(1027*1024))
RAM_percent = psutil.virtual_memory().percent
Swap = int(psutil.swap_memory().total/(1027*1024))
Swap_percent = psutil.swap_memory().percent
Net_sent = psutil.net_io_counters().bytes_sent
Net_recv = psutil.net_io_counters().bytes_recv
Net_spkg = psutil.net_io_counters().packets_sent
Net_rpkg = psutil.net_io_counters().packets_recv
BFH = r'%'
print " \033[1;32m主机名: %s\033[1;m" % Hostname
print " \033[1;32m系统版本: %s\033[1;m" % Sys_version
print " \033[1;32m开机时间:%s\033[1;m" % Boot_Start
print " \033[1;32m当前CPU使用率:%s%s\033[1;m" % (Cpu_usage,BFH)
print " \033[1;32m物理内存:%dM\t使用率:%s%s\033[1;m" % (RAM,RAM_percent,BFH)
print " \033[1;32mSwap内存:%dM\t使用率:%s%s\033[1;m" % (Swap,Swap_percent,BFH)
print " \033[1;32m发送:%d Byte\t发送包数:%d个\033[1;m" % (Net_sent,Net_spkg)
print " \033[1;32m接收:%d Byte\t接收包数:%d个\033[1;m" % (Net_recv,Net_rpkg)
for i in psutil.disk_partitions():
print " \033[1;32m盘符: %s 挂载点: %s 使用率: %s%s\033[1;m" % (i[0],i[1],psutil.disk_usage(i[1])[3],BFH)
for key in psutil.net_if_addrs().keys():
print " \033[1;32m网卡: %s IP: %s\033[1;m" % (key,psutil.net_if_addrs()[key][0][1])
示例5: ajax_sysinfo
def ajax_sysinfo():
sys_info['mem_usage_percent'] = psutil.virtual_memory().percent
sys_info['mem_total'] = psutil.virtual_memory().total
sys_info['mem_used'] = psutil.virtual_memory().used
sys_info['cpu_util'] = psutil.cpu_percent(percpu=True, interval=None)
#data = jsonify(results=["1", "2", "3"], name="Punit")
return jsonify(sysinfo=sys_info)
示例6: still_checkin
def still_checkin(self, hostname, ip_addr, port, load, data_dir, status="OK", max_tasks=2, cur_tasks=0):
###
# still_checkin : Check to see if the still entry already exists in the database, if it does update the timestamp, port, data_dir, and load.
# If does not exist then go ahead and create an entry.
###
s = self.Session()
if s.query(Still).filter(Still.hostname == hostname).count() > 0: # Check if the still already exists, if so just update the time
still = s.query(Still).filter(Still.hostname == hostname).one()
still.last_checkin = datetime.datetime.now()
still.status = status
# print("STILL_CHECKIN, test mode, setting load = 0, change back before release")
# still.current_load = 0
still.current_load = psutil.cpu_percent()
still.number_of_cores = psutil.cpu_count()
still.free_memory = round(psutil.virtual_memory().free / (1024 ** 3), 2)
still.total_memory = round(psutil.virtual_memory().total / (1024 ** 3), 2)
still.data_dir = data_dir
still.port = port
still.max_num_of_tasks = max_tasks
still.cur_num_of_tasks = cur_tasks
s.add(still)
else: # Still doesn't exist, lets add it
still = Still(hostname=hostname, ip_addr=ip_addr, port=port, current_load=load,
data_dir=data_dir, status=status, max_num_of_tasks=max_tasks, cur_num_of_tasks=cur_tasks)
s.add(still)
s.commit()
s.close()
return 0
示例7: CatchMEM
def CatchMEM(RunNumb, Interval, TimeStart):
"""
Funzione per catturare i dati della Memoria
Cattura le percentuali di utilizzo della memoria e della swap medie nell'intervallo richiesto
e le impacchetta per formare la risposta.
:param RunNumb: Il numero della Run corrente (al momento in cui è stato richiesto il lavoro al server)
:param Interval: Intervallo tra un campionamento e l'altro.
:param TimeStart: Tempo di avvio di questo campionamento, lo restituisco in uscita per poter calcolare la latenza.
:returns: Una tupla contenente i dati rilevati nel Interval.
"""
#selettori per andare a selezionare la percentuale di memoria utilizzata nelle rispettive liste ritornate da psutil
SelPerc = 3
Average_MEM, Average_SWP = 0, 0
for i in range(Interval):
#Average_MEM += psutil.phymem_usage()[SelPerc]/(Interval+1)
#Average_SWP += psutil.virtmem_usage()[SelPerc]/(Interval+1)
Average_MEM += psutil.virtual_memory().percent/(Interval+1)
Average_SWP += psutil.swap_memory().percent/(Interval+1)
time.sleep(1)
Average_MEM += psutil.virtual_memory().percent/(Interval+1)
Average_SWP += psutil.swap_memory().percent/(Interval+1)
ProbeManager.PutResult([ProbeID, RunNumb, "MEM", Average_MEM, Average_SWP, TimeStart])
示例8: performance
def performance(attribute):
""" A little smater routing system.
"""
data = None
if attribute == 'system':
data = { 'system': platform.system() }
elif attribute == 'processor':
data = { 'processor': platform.processor() }
elif attribute in ['cpu_count', 'cpucount'] :
data = { 'cpu_count': psutil.cpu_count() }
elif attribute == 'machine':
data = { 'machine': platform.machine() }
elif attribute in ['virtual_mem', 'virtualmem']:
data = { 'virtual_mem': psutil.virtual_memory().total }
elif attribute in ['virtual_mem_gb', 'virtualmemgb']:
data = { 'virtual_mem_gb': psutil.virtual_memory().total / (1024.0 ** 3) }
elif attribute == 'all':
data = {
'system': platform.system(),
'processor': platform.processor(),
'cpu_count': psutil.cpu_count(),
'machine': platform.machine(),
'virtual_mem': psutil.virtual_memory().total,
'virtual_mem_gb': psutil.virtual_memory().total / (1024.0 ** 3),
}
packet = json.dumps(data)
resp = Response(packet, status=200, mimetype='application/json')
return(resp)
示例9: get_mem_swap
def get_mem_swap(self,):
"""
Get memory and swap usage
"""
try:
# psutil >= 0.6.0
phymem = psutil.virtual_memory()
buffers = psutil.virtual_memory().buffers
cached = psutil.virtual_memory().cached
vmem = psutil.swap_memory()
except AttributeError:
# psutil > 0.4.0 and < 0.6.0
phymem = psutil.phymem_usage()
buffers = getattr(psutil, 'phymem_buffers', lambda: 0)()
cached = getattr(psutil, 'cached_phymem', lambda: 0)()
vmem = psutil.virtmem_usage()
mem_used = phymem.total - (phymem.free + buffers + cached)
return (
phymem.percent,
mem_used,
phymem.total,
vmem.percent,
vmem.used,
vmem.total)
示例10: __init__
def __init__(self, interval, history_len):
"""
:param interval: Collect statistics according to this interval.
:param history_len: Use this many to compute avg/max statistics.
"""
self.interval = interval
self.history_len = history_len
try:
import psutil # @UnresolvedImport @Reimport
except:
self._available = False
else:
self._available = True
self.cpu = Collect('cpu', lambda: psutil.cpu_percent(interval=0),
interval, history_len)
try:
# new in 0.8
psutil.virtual_memory().percent
get_mem = lambda: psutil.virtual_memory().percent
except:
get_mem = lambda: psutil.phymem_usage().percent
self.mem = Collect('mem', get_mem, interval, history_len)
try:
# new in 0.8
psutil.swap_memory().percent
get_mem = lambda: psutil.swap_memory().percent
except:
get_mem = lambda: psutil.virtmem_usage().percent
self.swap_mem = Collect('swap', get_mem, interval, history_len)
示例11: getSystemInfo
def getSystemInfo():
"""
Get a dictionary with some system/server info
return -- ["unix", "connectedUsers", "webServer", "cpuUsage", "totalMemory", "usedMemory", "loadAverage"]
"""
data = {}
# Get if server is running under unix/nt
data["unix"] = runningUnderUnix()
# General stats
data["connectedUsers"] = len(glob.tokens.tokens)
data["webServer"] = glob.conf.config["server"]["server"]
data["cpuUsage"] = psutil.cpu_percent()
data["totalMemory"] = "{0:.2f}".format(psutil.virtual_memory()[0]/1074000000)
data["usedMemory"] = "{0:.2f}".format(psutil.virtual_memory()[3]/1074000000)
# Unix only stats
if (data["unix"] == True):
data["loadAverage"] = os.getloadavg()
else:
data["loadAverage"] = (0,0,0)
return data
示例12: run
def run(self):
while self.RUN:
cpu = psutil.cpu_percent(interval=None)
ram = (psutil.virtual_memory()[0] - psutil.virtual_memory()[1]) / psutil.virtual_memory()[0] * 100
update_sensors.save_system_reading(cpu, ram)
time.sleep(settings.how_often_to_check_system)
示例13: check_mem
def check_mem(self):
# meminfo=psutil.virtual_memory()
mem_total=psutil.virtual_memory().total
mem_free=psutil.virtual_memory().free
# mem_free_percent= float( "%.2f" % (float(mem_free)/float(mem_total)) )
mem_free_percent= float( "%.1f" % (float(mem_free)/float(mem_total) *100 ) )
meminfo=[mem_total,mem_free,mem_free_percent]
return meminfo
示例14: __init__
def __init__(self):
super(NumpyDevice, self).__init__()
self.device_info = DeviceInfo(
desc="Python Numpy", memsize=virtual_memory().total,
memalign=8, version=numpy.__version__,
device_type="Hybrid",
max_work_group_size=None, max_work_item_sizes=None,
local_memsize=virtual_memory().total)
示例15: memInfo
def memInfo(self):
mem={"total":'', "used":'', "threshhold":False}
mem['total'] = psutil.virtual_memory().total
mem['used'] = psutil.virtual_memory().used
if (mem['total'] - mem['used']) <= conf.memLimit:
mem["threshhold"]=True
return mem