Skip to content

Instantly share code, notes, and snippets.

@ryu22e
Last active November 7, 2023 05:31
Show Gist options
  • Save ryu22e/87411710176fd1d0ba0f95b0e5f9d6e0 to your computer and use it in GitHub Desktop.
Save ryu22e/87411710176fd1d0ba0f95b0e5f9d6e0 to your computer and use it in GitHub Desktop.
sys.monitoring DEMO
def fizzbuzz(num):
if num % 3 == 0 and num % 5 == 0:
return "FizzBuzz"
elif num % 3 == 0:
return "Fizz"
elif num % 5 == 0:
return "Buzz"
else:
return str(num)
def main():
for i in range(1, 16):
print(fizzbuzz(i))
if __name__ == "__main__":
main()
#!/usr/bin/env python3.12
import argparse
import collections
import functools
import operator
import sys
from pathlib import Path
E = sys.monitoring.events
EVENTS = (
(E.PY_START, "start"),
(E.PY_RETURN, "return"),
(E.JUMP, "jump"),
(E.BRANCH, "branch"),
)
EVENT_SET = (
functools.reduce(operator.or_, [ev for (ev, _) in EVENTS], 0) | E.CALL
)
TOOL_ID = sys.monitoring.PROFILER_ID
def main(code):
events = []
# 1. 計測の準備
# ツールIDを登録
sys.monitoring.use_tool_id(TOOL_ID, "example-monitoring")
for event, event_name in EVENTS:
def record(*args, event_name=event_name):
events.append(event_name)
# フック関数を登録
sys.monitoring.register_callback(TOOL_ID, event, record)
# 監視するイベントを登録
sys.monitoring.set_events(TOOL_ID, EVENT_SET)
try:
# 2. 計測対象コードの実行
exec(code, globals())
except Exception:
pass
finally:
# 3. 計測の終了
# 監視するイベントの登録解除
sys.monitoring.set_events(TOOL_ID, 0)
# ツールIDを解放
sys.monitoring.free_tool_id(TOOL_ID)
c = collections.Counter(events)
print(c)
if __name__ == "__main__":
parser = argparse.ArgumentParser(prog="example-monitoring")
parser.add_argument('-s', '--source_path')
args = parser.parse_args()
p = Path(args.source_path)
code = compile(p.read_text(), str(p), "exec")
main(code)
@ryu22e
Copy link
Author

ryu22e commented Nov 3, 2023

Usage

$ python3.12 monitoring.py -s fizzbuzz.py
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
Counter({'branch': 61, 'start': 17, 'return': 17, 'jump': 15})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment