Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use Python threading to avoid creating temp files #39

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified .DS_Store
Binary file not shown.
31 changes: 11 additions & 20 deletions asitop/asitop.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@
import argparse
from collections import deque
from dashing import VSplit, HSplit, HGauge, HChart, VGauge
from .utils import *
from .utils import (build_enqueue_thread,
clear_console,
get_ram_metrics_dict,
get_soc_info,
parse_powermetrics,
run_powermetrics_process)

parser = argparse.ArgumentParser(
description='asitop: Performance monitoring CLI tool for Apple Silicon')
Expand All @@ -14,8 +19,6 @@
help='Interval for averaged values (seconds)')
parser.add_argument('--show_cores', type=bool, default=False,
help='Choose show cores mode')
parser.add_argument('--max_count', type=int, default=0,
help='Max show count to restart powermetrics')
args = parser.parse_args()


Expand Down Expand Up @@ -142,18 +145,16 @@ def main():

print("\n[2/3] Starting powermetrics process\n")

timecode = str(int(time.time()))

powermetrics_process = run_powermetrics_process(timecode,
interval=args.interval * 1000)
powermetrics_process = run_powermetrics_process(interval=args.interval * 1000)
queue, _thread = build_enqueue_thread(powermetrics_process.stdout)

print("\n[3/3] Waiting for first reading...\n")

def get_reading(wait=0.1):
ready = parse_powermetrics(timecode=timecode)
ready = parse_powermetrics(queue)
while not ready:
time.sleep(wait)
ready = parse_powermetrics(timecode=timecode)
ready = parse_powermetrics(queue)
return ready

ready = get_reading()
Expand All @@ -169,18 +170,9 @@ def get_avg(inlist):

clear_console()

count=0
try:
while True:
if args.max_count > 0:
if count >= args.max_count:
count = 0
powermetrics_process.terminate()
timecode = str(int(time.time()))
powermetrics_process = run_powermetrics_process(
timecode, interval=args.interval * 1000)
count += 1
ready = parse_powermetrics(timecode=timecode)
ready = parse_powermetrics(queue)
if ready:
cpu_metrics_dict, gpu_metrics_dict, thermal_pressure, bandwidth_metrics, timestamp = ready

Expand Down Expand Up @@ -401,7 +393,6 @@ def get_avg(inlist):

ui.display()

time.sleep(args.interval)

except KeyboardInterrupt:
print("Stopping...")
Expand Down
51 changes: 37 additions & 14 deletions asitop/utils.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
import os
import glob
import subprocess
from queue import LifoQueue
from subprocess import PIPE
from threading import Thread
import psutil
from .parsers import *
import plistlib


def parse_powermetrics(path='/tmp/asitop_powermetrics', timecode="0"):
data = None
def parse_powermetrics(queue):
try:
with open(path+timecode, 'rb') as fp:
data = fp.read()
data = data.split(b'\x00')
powermetrics_parse = plistlib.loads(data[-1])
# a Last in First out queue
data = queue.get()
powermetrics_parse = plistlib.loads(data)
thermal_pressure = parse_thermal_pressure(powermetrics_parse)
cpu_metrics_dict = parse_cpu_metrics(powermetrics_parse)
gpu_metrics_dict = parse_gpu_metrics(powermetrics_parse)
Expand Down Expand Up @@ -43,20 +42,44 @@ def clear_console():
def convert_to_GB(value):
return round(value/1024/1024/1024, 1)


def run_powermetrics_process(timecode, nice=10, interval=1000):
def enqueue_powermetrics(buffered_reader, queue_in):
"""
a helper to convert the output of `powermetrics`
into list of plist strings.

buffered_reader: stdout of the `powermetrics` process
queue_in: a LIFO queue, will also be provided to the parser
"""
buffer = b''
for line in buffered_reader:
# magic string
if line.startswith(b"\x00"):
queue_in.put(buffer)
buffer = line[1:]
else:
buffer += line

def build_enqueue_thread(powermetrics_stdout):
"""
build a thread to run enqueue_powermetrics()
returns:
queue: the LIFO queue, containing plist strings
equeue_thread: the identifier of the thread
"""
queue = LifoQueue()
enqueue_thread = Thread(target=enqueue_powermetrics,
args=(powermetrics_stdout, queue))
enqueue_thread.start()
return queue, enqueue_thread

def run_powermetrics_process(nice=10, interval=1000):
#ver, *_ = platform.mac_ver()
#major_ver = int(ver.split(".")[0])
for tmpf in glob.glob("/tmp/asitop_powermetrics*"):
os.remove(tmpf)
output_file_flag = "-o"
command = " ".join([
"sudo nice -n",
str(nice),
"powermetrics",
"--samplers cpu_power,gpu_power,thermal",
output_file_flag,
"/tmp/asitop_powermetrics"+timecode,
"-f plist",
"-i",
str(interval)
Expand Down