twatch.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #! /usr/bin/env python
  2. # SPDX-License-Identifier: GPL-2.0-only
  3. # -*- python -*-
  4. # -*- coding: utf-8 -*-
  5. # twatch - Experimental use of the perf python interface
  6. # Copyright (C) 2011 Arnaldo Carvalho de Melo <acme@redhat.com>
  7. #
  8. import perf
  9. def main(context_switch = 0, thread = -1):
  10. cpus = perf.cpu_map()
  11. threads = perf.thread_map(thread)
  12. evsel = perf.evsel(type = perf.TYPE_SOFTWARE,
  13. config = perf.COUNT_SW_DUMMY,
  14. task = 1, comm = 1, mmap = 0, freq = 0,
  15. wakeup_events = 1, watermark = 1,
  16. sample_id_all = 1, context_switch = context_switch,
  17. sample_type = perf.SAMPLE_PERIOD | perf.SAMPLE_TID | perf.SAMPLE_CPU)
  18. """What we want are just the PERF_RECORD_ lifetime events for threads,
  19. using the default, PERF_TYPE_HARDWARE + PERF_COUNT_HW_CYCLES & freq=1
  20. (the default), makes perf reenable irq_vectors:local_timer_entry, when
  21. disabling nohz, not good for some use cases where all we want is to get
  22. threads comes and goes... So use (perf.TYPE_SOFTWARE, perf_COUNT_SW_DUMMY,
  23. freq=0) instead."""
  24. evsel.open(cpus = cpus, threads = threads);
  25. evlist = perf.evlist(cpus, threads)
  26. evlist.add(evsel)
  27. evlist.mmap()
  28. while True:
  29. evlist.poll(timeout = -1)
  30. for cpu in cpus:
  31. event = evlist.read_on_cpu(cpu)
  32. if not event:
  33. continue
  34. print("cpu: {0}, pid: {1}, tid: {2} {3}".format(event.sample_cpu,
  35. event.sample_pid,
  36. event.sample_tid,
  37. event))
  38. if __name__ == '__main__':
  39. """
  40. To test the PERF_RECORD_SWITCH record, pick a pid and replace
  41. in the following line.
  42. Example output:
  43. cpu: 3, pid: 31463, tid: 31593 { type: context_switch, next_prev_pid: 31463, next_prev_tid: 31593, switch_out: 1 }
  44. cpu: 1, pid: 31463, tid: 31489 { type: context_switch, next_prev_pid: 31463, next_prev_tid: 31489, switch_out: 1 }
  45. cpu: 2, pid: 31463, tid: 31496 { type: context_switch, next_prev_pid: 31463, next_prev_tid: 31496, switch_out: 1 }
  46. cpu: 3, pid: 31463, tid: 31491 { type: context_switch, next_prev_pid: 31463, next_prev_tid: 31491, switch_out: 0 }
  47. It is possible as well to use event.misc & perf.PERF_RECORD_MISC_SWITCH_OUT
  48. to figure out if this is a context switch in or out of the monitored threads.
  49. If bored, please add command line option parsing support for these options :-)
  50. """
  51. # main(context_switch = 1, thread = 31463)
  52. main()