반응형

 


작성일: 2024년 1월 9일

 

Intel CPU를 사용하는 Macbook을 사용했을 때는 아래와 같이 CPU 온도를 확인했었다.

$ sudo powermetrics -n 1 --samplers smc

 

그런데 m1 CPU를 사용하는 Macbook을 구입한 뒤로는 위 명령이 쓸모없게 되었다. 

왜냐하면 아래처럼 에러가 발생하기 때문이다.

$ powermetrics -n 1 --samplers smc

powermetrics: unrecognized sampler: smc

$

 

 

M1, M2 CPU를 장착한 Mac에서 CPU 온도 확인하는 방법.

 

 

그렇다면, m1 CPU를 장착한 Macbook에서는 어떻게 CPU 온도를 확인할까?

아래처럼 Hot 이라는 앱을 설치하면 된다.

 

$ brew install --cask hot
참고로 자세한 설명은 아래 공식 홈페이지를 읽어볼 것 !
  https://formulae.brew.sh/cask/hot

 

brew 명령으로 hot 앱이 설치되었다면, hot 앱을 구동한다. 아래 화면과 같이 m1 cpu 온도가 짠~하고 보여질 것이다.

 

macOS m1 CPU 온도 정보 확인 (Hot 앱)

 

macOS m1 CPU 온도 확인을 위한 Hot 앱

 

Parallels로 Windows 11 구동하고, 이것저것 업무에 필요한 앱을 많이 구동했는데 섭씨 31도 밖에 안 되네.

M1 CPU를 좋아할 수 밖에 없는 이유가 바로 이런 것 때문 ^^

 


 

'MacOS' 카테고리의 다른 글

macOS에 설치할 App (앱, 프로그램)  (0) 2023.11.23
macOS Sonoma에서 Parallels 17 비정상 동작  (0) 2023.11.03
Mac M1 프린터 드라이버 설치  (0) 2022.02.21
Mac 에서 기본 앱 설정 변경  (0) 2022.02.21
Mac에서 연말정산  (0) 2022.01.29
반응형

Go Language로 특정 Process의 CPU, Memory 사용량을 계산하고 싶다면,

아래의 코드를 Build해서 사용하면 된다.

 

참고: Linux, MacOS, Unix, Windows 모두 동작하는 코드임.

 

 

// Filename: proc_usage.go

package main

import (
	"errors"
	"fmt"
	"io/ioutil"
	"math"
	"os/exec"
	"path"
	"runtime"
	"strconv"
	"strings"
	"sync"
)

const (
	statTypePS   = "ps"
	statTypeProc = "proc"
)

// SysInfo will record cpu and memory data
type SysInfo struct {
	CPU    float64
	Memory float64
}

// Stat will store CPU time struct
type Stat struct {
	utime  float64
	stime  float64
	cutime float64
	cstime float64
	start  float64
	rss    float64
	uptime float64
}

type fn func(int) (*SysInfo, error)

var fnMap map[string]fn
var platform string
var history map[int]Stat
var historyLock sync.Mutex
var eol string

// Linux platform
var clkTck float64 = 100    // default
var pageSize float64 = 4096 // default

func init() {
	platform = runtime.GOOS
	if eol = "\n"; strings.Index(platform, "win") == 0 {
		platform = "win"
		eol = "\r\n"
	}
	history = make(map[int]Stat)
	fnMap = make(map[string]fn)
	fnMap["darwin"] = wrapper("ps")
	fnMap["sunos"] = wrapper("ps")
	fnMap["freebsd"] = wrapper("ps")
	fnMap["openbsd"] = wrapper("proc")
	fnMap["aix"] = wrapper("ps")
	fnMap["linux"] = wrapper("proc")
	fnMap["netbsd"] = wrapper("proc")
	fnMap["win"] = wrapper("win")

	if platform == "linux" || platform == "netbsd" || platform == "openbsd" {
		initProc()
	}
}

func initProc() {
	clkTckStdout, err := exec.Command("getconf", "CLK_TCK").Output()
	if err == nil {
		clkTck = parseFloat(formatStdOut(clkTckStdout, 0)[0])
	}

	pageSizeStdout, err := exec.Command("getconf", "PAGESIZE").Output()
	if err == nil {
		pageSize = parseFloat(formatStdOut(pageSizeStdout, 0)[0])
	}

}

func wrapper(statType string) func(pid int) (*SysInfo, error) {
	return func(pid int) (*SysInfo, error) {
		return stat(pid, statType)
	}
}

func formatStdOut(stdout []byte, userfulIndex int) []string {
	infoArr := strings.Split(string(stdout), eol)[userfulIndex]
	ret := strings.Fields(infoArr)
	return ret
}

func parseFloat(val string) float64 {
	floatVal, _ := strconv.ParseFloat(val, 64)
	return floatVal
}

func statFromPS(pid int) (*SysInfo, error) {
	sysInfo := &SysInfo{}
	args := "-o pcpu,rss -p"
	if platform == "aix" {
		args = "-o pcpu,rssize -p"
	}
	stdout, _ := exec.Command("ps", args, strconv.Itoa(pid)).Output()
	ret := formatStdOut(stdout, 1)
	if len(ret) == 0 {
		return sysInfo, errors.New("Can't find process with this PID: " + strconv.Itoa(pid))
	}
	sysInfo.CPU = parseFloat(ret[0])
	sysInfo.Memory = parseFloat(ret[1]) * 1024
	return sysInfo, nil
}

func statFromProc(pid int) (*SysInfo, error) {
	sysInfo := &SysInfo{}
	uptimeFileBytes, err := ioutil.ReadFile(path.Join("/proc", "uptime"))
	if err != nil {
		return nil, err
	}
	uptime := parseFloat(strings.Split(string(uptimeFileBytes), " ")[0])

	procStatFileBytes, err := ioutil.ReadFile(path.Join("/proc", strconv.Itoa(pid), "stat"))
	if err != nil {
		return nil, err
	}
	splitAfter := strings.SplitAfter(string(procStatFileBytes), ")")

	if len(splitAfter) == 0 || len(splitAfter) == 1 {
		return sysInfo, errors.New("Can't find process with this PID: " + strconv.Itoa(pid))
	}
	infos := strings.Split(splitAfter[1], " ")
	stat := &Stat{
		utime:  parseFloat(infos[12]),
		stime:  parseFloat(infos[13]),
		cutime: parseFloat(infos[14]),
		cstime: parseFloat(infos[15]),
		start:  parseFloat(infos[20]) / clkTck,
		rss:    parseFloat(infos[22]),
		uptime: uptime,
	}

	_stime := 0.0
	_utime := 0.0

	historyLock.Lock()
	defer historyLock.Unlock()

	_history := history[pid]

	if _history.stime != 0 {
		_stime = _history.stime
	}

	if _history.utime != 0 {
		_utime = _history.utime
	}
	total := stat.stime - _stime + stat.utime - _utime
	total = total / clkTck

	seconds := stat.start - uptime
	if _history.uptime != 0 {
		seconds = uptime - _history.uptime
	}

	seconds = math.Abs(seconds)
	if seconds == 0 {
		seconds = 1
	}

	history[pid] = *stat
	sysInfo.CPU = (total / seconds) * 100
	sysInfo.Memory = stat.rss * pageSize
	return sysInfo, nil
}

func stat(pid int, statType string) (*SysInfo, error) {
	switch statType {
	case statTypePS:
		return statFromPS(pid)
	case statTypeProc:
		return statFromProc(pid)
	default:
		return nil, fmt.Errorf("Unsupported OS %s", runtime.GOOS)
	}
}

// GetStat will return current system CPU and memory data
func GetStat(pid int) (*SysInfo, error) {
	sysInfo, err := fnMap[platform](pid)
	return sysInfo, err
}

 

 

 

// Filename: main.go

package main

import (
    "os"
    "fmt"
    "time"
    "strconv"
)

func main() {
    myPid, _ := strconv.Atoi(os.Args[1])

    for i:= 0; i < 100; i++ {
        sysInfo, _ := GetStat(myPid)
        fmt.Println("CPU Usage     :", sysInfo.CPU)
        fmt.Println("Mem Usage(RSS):", sysInfo.Memory)
        time.Sleep(5 * time.Second)
    }
}

 

위와 같이 Go source code를 모두 작성했다면, 아래처럼 build하고 실행하면 된다.

 

$ go mod init andrew.space/proc_usage
go: creating new go.mod: module andrew.space/proc_usage
go: to add module requirements and sums:
	go mod tidy
    
$ go mod tidy

$ go build

$ ./proc_usage 4314
CPU Usage     : 52.92167225853122
Mem Usage(RSS): 2.018664448e+09
CPU Usage     : 39.800000000000004
Mem Usage(RSS): 2.018664448e+09
CPU Usage     : 47.30538922366738
Mem Usage(RSS): 2.018664448e+09
...
...

 

top 명령으로 본 것과 결과가 동일했다.

반응형

시스템 알람을 발생시키는 테스트를 하거나 Kubernetes의 Horizontal Pod Autoscaler 기능 테스트를 할 때,

CPU 부하를 발생시키는 명령 도구가 있으면 편하다.

아래와 같이 설치하고 테스트하면 된다. (설명은 생략하고, 그냥 따라해보자~)

 

##
## 설치
##

$ yum install -y stress

$ stress --help
...

##
## 30초 동안 3000ms의 CPU 과부하를 유발하기.
##
$ stress --cpu 3 --timeout 30s

##
## 500MB의 메모리 과부하를 유발하기
##  --vm : Worker 개수
##  --vm-hang : malloc 실행 후 free하기 전까지 sleep할 시간(초)
##
$ stress --vm 1 --vm-bytes 500M --vm-hang 1

 

블로그 작성자: sejong.jeonjo@gmail.com

 

 

반응형

 

아래의 Go App을 Build해서 Kubernetes Worker Node에서 돌려보면,

각 Container가 사용하는 CPU Set(즉, Container App이 Pinning한 Core 정보), Memory Hugepages, Network 주소 및 PCI 정보를 알 수 있다.

 

 

https://github.com/openshift/app-netutil/tree/master/samples/go_app

 

GitHub - openshift/app-netutil: app-netutil is a library that provides API methods for applications to get pod network informati

app-netutil is a library that provides API methods for applications to get pod network information. - GitHub - openshift/app-netutil: app-netutil is a library that provides API methods for applicat...

github.com

 

그리고, 위 Repository에 DPDK example app container도 있으니까, DPDK 테스트할 때도 이용하면 좋다.

 

 

 

 

반응형

 

NUMA with Linux

https://lunatine.net/2016/07/14/numa-with-linux/

 

NUMA with Linux :: Lunatine's Box — Lunatine's Box

linuxnumainterleaved memoryinterleavenumctlnumad 3236 Words 2016-07-14 15:18 +0900

lunatine.net

https://frankdenneman.nl/2016/07/07/numa-deep-dive-part-1-uma-numa/

 

NUMA Deep Dive Part 1: From UMA to NUMA - frankdenneman.nl

Non-uniform memory access (NUMA) is a shared memory architecture used in today’s multiprocessing systems. Each CPU is assigned its own local memory and can access memory from other CPUs in the system. Local memory access provides a low latency – high

frankdenneman.nl

 

 

 

 

HugePages

https://luis-javier-arizmendi-alonso.medium.com/enhanced-platform-awareness-epa-in-openshift-part-i-hugepages-a28e640fabf6

 

Enhanced Platform Awareness (EPA) in OpenShift — Part I, HugePages

This series of posts will show how to configure EPA support in OpenShift 4. In this part you will see 1GB HugePages configuration and usage

luis-javier-arizmendi-alonso.medium.com

 

CPU Pinning

https://luis-javier-arizmendi-alonso.medium.com/enhanced-platform-awareness-epa-in-openshift-part-ii-cpu-pinning-8e397fc9fe08

 

Enhanced Platform Awareness (EPA) in OpenShift — Part II, CPU pinning

This is the second part about how to configure an EPA ready OpenShift worker node, covering the CPU pinning and CPU isolation…

luis-javier-arizmendi-alonso.medium.com

 

 

NUMA Topology Awareness

https://luis-javier-arizmendi-alonso.medium.com/enhanced-platform-awareness-epa-in-openshift-part-iii-numa-topology-awareness-180c91c40800

 

Enhanced Platform Awareness (EPA) in OpenShift — Part III, NUMA Topology Awareness

This time we are going to focus on how we can assure that the CPU scheduling takes into account the NUMA topology of the processor

luis-javier-arizmendi-alonso.medium.com

 

 

SR-IOV, DPDK, RDMA

https://medium.com/swlh/enhanced-platform-awareness-epa-in-openshift-part-iv-sr-iov-dpdk-and-rdma-1cc894c4b7d0

 

Enhanced Platform Awareness (EPA) in OpenShift — Part IV, SR-IOV, DPDK and RDMA

In this Post we’ll review some concepts that help to minimize random latencies and improve the network performance: SR-IOV, DPDK, and RDMA.

medium.com

 

 

반응형

 

 

http://egloos.zum.com/rousalome/v/10025064

 

[리눅스] 프로세스를 지정한 CPU에서 실행: sched_setaffinity() 함수

소형 임베디드 장비를 제외하고는 대부분 시스템은 멀티 CPU 코어 환경에서 개발됩니다. 멀티 프로세스(Multiprocess) 기반으로 작성된 데몬을 실행하면 여러 CPU 코어에 적당히 나뉘어 실행되는 것

egloos.zum.com

 

 

반응형

 

KVM, OpenStack, Kubernetes, OCP 등을 사용하다보면 VM에서 또는 Container 내부에서 CPU를 Pinning하거나 NUMA Node를 지정해야 할 경우가 있는데, 이런 CPU Pinning 설정/관리에 대한 내용을 기록해볼까~~~하고 마음을 먹었다. 그러나 너무 잘 작성한 블로그와 WebDocs가 있어서 그냥 Link만 걸어두기로 마음을 바꾸었다. :)

 

 

https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/5/html/virtualization/ch33s08

 

33.8. Setting KVM processor affinities Red Hat Enterprise Linux 5 | Red Hat Customer Portal

The Red Hat Customer Portal delivers the knowledge, expertise, and guidance available through your Red Hat subscription.

access.redhat.com

 

 

 

https://mhsamsal.wordpress.com/2020/05/12/how-to-perform-cpu-pinning-for-kvm-virtual-machines-and-docker-containers/

 

How to Perform CPU Pinning for KVM Virtual Machines and Docker Containers

Note: This post provides technical details for our paper “The Art of CPU-Pinning: Evaluating and Improving the Performance of Virtualization and Containerization Platforms” published in…

mhsamsal.wordpress.com

 

 

 

https://superuser.com/questions/1519358/qemu-kvm-cpu-pinning

 

QEMU/KVM cpu pinning

I have set up my VM with pci passthrough and now I am trying to set up cpupinning. How do I verify that it does in fact work? My config regarding cpu parameters: ... <vcpu placement="static">...

superuser.com

 

 

+ Recent posts