Título alternativo: How to get CPU usage per core with python
Teste de indexação do google ;)

Mais um post para a série “Parseando o /proc” [1]. Dessa vez sem motivo explícito, apenas diversão!

Ambientes de testes:

  • Ubunto c/ 1 núcleo e Python 2.6
  • Ubunto c/ 2 núcleos e Python 2.6
  • CentOS c/ 4 núcleos e Python 2.4.
  • Comparei os resultados através do htop e obtive uma proximidade alta nos valores, as diferenças se dão provavelmente pelo momento e duração da medição!

    Quem puder testar em ambientes com mais núcleos ou uso intensivo da CPU e comparar com as ferramentas do sistema por favor me de um feedback

    E quem rir da qualidade do meu inglês nos comentários eu vou banir o ip! :)

    ?View Code PYTHON
    #!/usr/bin/env python
    import time
    import os
     
    # [ reference ]
    # Detect number of cpus
    # http://www.boduch.ca/2009/06/python-cpus.html
    # Get cpu usage (But this example is not working 100%)
    # http://ubuntuforums.org/showpost.php?p=853257&postcount=4
     
    INTERVAL = 2
     
    class CPUUsage:
        def __init__(self):
            self.cores = self.detectCPUs()
     
        def createCoreArray(self):
            cores = []
            for i in range(self.cores):
                cores.append("")
            return cores
     
        def detectCPUs(self):
            if hasattr(os, "sysconf"):
                if os.sysconf_names.has_key("SC_NPROCESSORS_ONLN"):
                    ncpus = os.sysconf("SC_NPROCESSORS_ONLN")
                    if isinstance(ncpus, int) and ncpus > 0:
                        return ncpus
            return 1 # Default
     
        def getTimeList(self):
            core = self.createCoreArray()
     
            statFile = file("/proc/stat", "r")
            if not self.cores == 1:
                statFile.readline()
     
            # this FOR will split lines from proc/stat for every active core
            for cid in range(self.cores):
                # when have just one core, split a different range
                if self.cores == 1:
                    core[cid] = statFile.readline().split(" ")[2:7] # 2:6
                else:
                    core[cid] = statFile.readline().split(" ")[1:6] # 1:5
            statFile.close()
     
            # convert all itens in splited list from STR to INT for every core
            for i in range(len(core[0])):
                for cid in range(self.cores):
                    core[cid][i] = int(core[cid][i])
     
            # return the core list now with INT values inside their cpu values
            # like this: ([core,1,values],[core,2,values],[core,3,values])
            return core
     
        def deltaTime(self,interval):
            coreT1=self.createCoreArray()
            coreT2=self.createCoreArray()
     
            # get core TIME 1 state per core
            coreT1 = self.getTimeList()
            # wait X seconds to get new state core
            time.sleep(interval)
            # get core TIME 2 state per core
            coreT2 = self.getTimeList()
     
            #Get the diference of coreT2.item[i] and coreT1.item[i] for every core
            for i in range(len(coreT1[0])):
                for cid in range(self.cores):
                    coreT2[cid][i] -= coreT1[cid][i]
            return coreT2
     
        def Usage(self):
            core = self.createCoreArray()
            cpuUsage = []
     
            core = self.deltaTime(INTERVAL)
     
            for cid in range(self.cores):
                # sum of user,system and nice usage
                tmp_use = core[cid][0] + core[cid][1]+core[cid][2]
                # 100.00 * usage / sum of usage + idle + waiting
                usage = "%.2f" % ((100.00 * tmp_use) / sum(core[cid]))
                cpuUsage.append(usage)
            return cpuUsage
     
    if __name__ == "__main__":
        # Show usage per core
        #print CPUUsage().Usage()
     
        x = 0
        for item in CPUUsage().Usage():
            x = x + 1
            print "CPU[%s]: %s" % (str(x),str(item))

    One Response to “Uso da CPU (por núcleo) em Python ou parseando o /proc/stat”

    1. Sérgio Berlotto Says:

      Ficou muito bom !
      Aqui, CentoOS com 2 quad-core mostrou o uso igual ao htop.
      Só demorou mesmo no parse como citado …
      Cool !

    Leave a Reply

    *
    To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
    Click to hear an audio file of the anti-spam word