Last active
October 7, 2021 10:22
-
-
Save VincenzoLaSpesa/a4a5030b30dcef3f49a97ebbb8b4e11b to your computer and use it in GitHub Desktop.
A quick&dirty way for logging the cpu and memory usage of a specific project. Probably cross platform
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import pprint | |
| import psutil | |
| import time | |
| import csv | |
| import argparse | |
| import os | |
| class Writer: | |
| stream=None | |
| writer=None | |
| def __init__(self, filename= ""): | |
| if(len(filename)> 0): | |
| self.stream = open(args.output, 'w', newline='') | |
| self.writer = csv.writer(self.stream, delimiter="\t",quotechar='"', quoting=csv.QUOTE_MINIMAL) | |
| def __del__(self): | |
| if self.stream: | |
| self.stream.close() | |
| def print(self, row: list): | |
| print(row) | |
| if self.stream: | |
| self.writer.writerow(row) | |
| self.stream.flush() | |
| def get_process(name:str): | |
| for proc in psutil.process_iter(): | |
| try: | |
| # Get process name & pid from process object. | |
| if name in proc.name(): | |
| return proc.pid, proc | |
| except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): | |
| pass | |
| return -1,None | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument('pname', type=str,nargs='?', help='name of the process to watch') | |
| parser.add_argument("-o", "--output",type=str, help="Where to write the csv output", default="") | |
| parser.add_argument("-t", "--trigger",type=str, help="When a file named like that will be present the script will stop") | |
| args = parser.parse_args() | |
| pprint.pprint(args) | |
| if not args.pname: | |
| print("I need a process to watch") | |
| parser.print_help() | |
| quit() | |
| writer=Writer(args.output) | |
| pid, proc= get_process(args.pname) | |
| if pid < 0: | |
| print("There is no process named", args.pname) | |
| quit() | |
| base=proc.cpu_times().user | |
| t=time.time() | |
| writer.print(("t","cpu_time","memory_size")) | |
| while True: | |
| time.sleep(1) | |
| d = proc.as_dict(attrs=['pid', 'name','cpu_times', 'memory_full_info']) | |
| v=(time.time()-t, d['cpu_times'].user-base, d['memory_full_info'].uss/(1024*1024*1024) ) | |
| base=d['cpu_times'].user | |
| writer.print(v) | |
| if args.trigger and os.path.isfile(args.trigger): | |
| quit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment