Last active
November 7, 2023 05:31
-
-
Save ryu22e/87411710176fd1d0ba0f95b0e5f9d6e0 to your computer and use it in GitHub Desktop.
sys.monitoring DEMO
This file contains 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
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() |
This file contains 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
#!/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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage