intel_pstate_tracer.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. #
  4. """ This utility can be used to debug and tune the performance of the
  5. intel_pstate driver. This utility can be used in two ways:
  6. - If there is Linux trace file with pstate_sample events enabled, then
  7. this utility can parse the trace file and generate performance plots.
  8. - If user has not specified a trace file as input via command line parameters,
  9. then this utility enables and collects trace data for a user specified interval
  10. and generates performance plots.
  11. Prerequisites:
  12. Python version 2.7.x
  13. gnuplot 5.0 or higher
  14. gnuplot-py 1.8
  15. (Most of the distributions have these required packages. They may be called
  16. gnuplot-py, phython-gnuplot. )
  17. HWP (Hardware P-States are disabled)
  18. Kernel config for Linux trace is enabled
  19. see print_help(): for Usage and Output details
  20. """
  21. from __future__ import print_function
  22. from datetime import datetime
  23. import subprocess
  24. import os
  25. import time
  26. import re
  27. import sys
  28. import getopt
  29. import Gnuplot
  30. from numpy import *
  31. from decimal import *
  32. __author__ = "Srinivas Pandruvada"
  33. __copyright__ = " Copyright (c) 2017, Intel Corporation. "
  34. __license__ = "GPL version 2"
  35. MAX_CPUS = 256
  36. # Define the csv file columns
  37. C_COMM = 18
  38. C_GHZ = 17
  39. C_ELAPSED = 16
  40. C_SAMPLE = 15
  41. C_DURATION = 14
  42. C_LOAD = 13
  43. C_BOOST = 12
  44. C_FREQ = 11
  45. C_TSC = 10
  46. C_APERF = 9
  47. C_MPERF = 8
  48. C_TO = 7
  49. C_FROM = 6
  50. C_SCALED = 5
  51. C_CORE = 4
  52. C_USEC = 3
  53. C_SEC = 2
  54. C_CPU = 1
  55. global sample_num, last_sec_cpu, last_usec_cpu, start_time, testname
  56. # 11 digits covers uptime to 115 days
  57. getcontext().prec = 11
  58. sample_num =0
  59. last_sec_cpu = [0] * MAX_CPUS
  60. last_usec_cpu = [0] * MAX_CPUS
  61. def print_help():
  62. print('intel_pstate_tracer.py:')
  63. print(' Usage:')
  64. print(' If the trace file is available, then to simply parse and plot, use (sudo not required):')
  65. print(' ./intel_pstate_tracer.py [-c cpus] -t <trace_file> -n <test_name>')
  66. print(' Or')
  67. print(' ./intel_pstate_tracer.py [--cpu cpus] ---trace_file <trace_file> --name <test_name>')
  68. print(' To generate trace file, parse and plot, use (sudo required):')
  69. print(' sudo ./intel_pstate_tracer.py [-c cpus] -i <interval> -n <test_name>')
  70. print(' Or')
  71. print(' sudo ./intel_pstate_tracer.py [--cpu cpus] --interval <interval> --name <test_name>')
  72. print(' Optional argument:')
  73. print(' cpus: comma separated list of CPUs')
  74. print(' Output:')
  75. print(' If not already present, creates a "results/test_name" folder in the current working directory with:')
  76. print(' cpu.csv - comma seperated values file with trace contents and some additional calculations.')
  77. print(' cpu???.csv - comma seperated values file for CPU number ???.')
  78. print(' *.png - a variety of PNG format plot files created from the trace contents and the additional calculations.')
  79. print(' Notes:')
  80. print(' Avoid the use of _ (underscore) in test names, because in gnuplot it is a subscript directive.')
  81. print(' Maximum number of CPUs is {0:d}. If there are more the script will abort with an error.'.format(MAX_CPUS))
  82. print(' Off-line CPUs cause the script to list some warnings, and create some empty files. Use the CPU mask feature for a clean run.')
  83. print(' Empty y range warnings for autoscaled plots can occur and can be ignored.')
  84. def plot_perf_busy_with_sample(cpu_index):
  85. """ Plot method to per cpu information """
  86. file_name = 'cpu{:0>3}.csv'.format(cpu_index)
  87. if os.path.exists(file_name):
  88. output_png = "cpu%03d_perf_busy_vs_samples.png" % cpu_index
  89. g_plot = common_all_gnuplot_settings(output_png)
  90. g_plot('set yrange [0:40]')
  91. g_plot('set y2range [0:200]')
  92. g_plot('set y2tics 0, 10')
  93. g_plot('set title "{} : cpu perf busy vs. sample : CPU {:0>3} : {:%F %H:%M}"'.format(testname, cpu_index, datetime.now()))
  94. # Override common
  95. g_plot('set xlabel "Samples"')
  96. g_plot('set ylabel "P-State"')
  97. g_plot('set y2label "Scaled Busy/performance/io-busy(%)"')
  98. set_4_plot_linestyles(g_plot)
  99. g_plot('plot "' + file_name + '" using {:d}:{:d} with linespoints linestyle 1 axis x1y2 title "performance",\\'.format(C_SAMPLE, C_CORE))
  100. g_plot('"' + file_name + '" using {:d}:{:d} with linespoints linestyle 2 axis x1y2 title "scaled-busy",\\'.format(C_SAMPLE, C_SCALED))
  101. g_plot('"' + file_name + '" using {:d}:{:d} with linespoints linestyle 3 axis x1y2 title "io-boost",\\'.format(C_SAMPLE, C_BOOST))
  102. g_plot('"' + file_name + '" using {:d}:{:d} with linespoints linestyle 4 axis x1y1 title "P-State"'.format(C_SAMPLE, C_TO))
  103. def plot_perf_busy(cpu_index):
  104. """ Plot some per cpu information """
  105. file_name = 'cpu{:0>3}.csv'.format(cpu_index)
  106. if os.path.exists(file_name):
  107. output_png = "cpu%03d_perf_busy.png" % cpu_index
  108. g_plot = common_all_gnuplot_settings(output_png)
  109. g_plot('set yrange [0:40]')
  110. g_plot('set y2range [0:200]')
  111. g_plot('set y2tics 0, 10')
  112. g_plot('set title "{} : perf busy : CPU {:0>3} : {:%F %H:%M}"'.format(testname, cpu_index, datetime.now()))
  113. g_plot('set ylabel "P-State"')
  114. g_plot('set y2label "Scaled Busy/performance/io-busy(%)"')
  115. set_4_plot_linestyles(g_plot)
  116. g_plot('plot "' + file_name + '" using {:d}:{:d} with linespoints linestyle 1 axis x1y2 title "performance",\\'.format(C_ELAPSED, C_CORE))
  117. g_plot('"' + file_name + '" using {:d}:{:d} with linespoints linestyle 2 axis x1y2 title "scaled-busy",\\'.format(C_ELAPSED, C_SCALED))
  118. g_plot('"' + file_name + '" using {:d}:{:d} with linespoints linestyle 3 axis x1y2 title "io-boost",\\'.format(C_ELAPSED, C_BOOST))
  119. g_plot('"' + file_name + '" using {:d}:{:d} with linespoints linestyle 4 axis x1y1 title "P-State"'.format(C_ELAPSED, C_TO))
  120. def plot_durations(cpu_index):
  121. """ Plot per cpu durations """
  122. file_name = 'cpu{:0>3}.csv'.format(cpu_index)
  123. if os.path.exists(file_name):
  124. output_png = "cpu%03d_durations.png" % cpu_index
  125. g_plot = common_all_gnuplot_settings(output_png)
  126. # Should autoscale be used here? Should seconds be used here?
  127. g_plot('set yrange [0:5000]')
  128. g_plot('set ytics 0, 500')
  129. g_plot('set title "{} : durations : CPU {:0>3} : {:%F %H:%M}"'.format(testname, cpu_index, datetime.now()))
  130. g_plot('set ylabel "Timer Duration (MilliSeconds)"')
  131. # override common
  132. g_plot('set key off')
  133. set_4_plot_linestyles(g_plot)
  134. g_plot('plot "' + file_name + '" using {:d}:{:d} with linespoints linestyle 1 axis x1y1'.format(C_ELAPSED, C_DURATION))
  135. def plot_loads(cpu_index):
  136. """ Plot per cpu loads """
  137. file_name = 'cpu{:0>3}.csv'.format(cpu_index)
  138. if os.path.exists(file_name):
  139. output_png = "cpu%03d_loads.png" % cpu_index
  140. g_plot = common_all_gnuplot_settings(output_png)
  141. g_plot('set yrange [0:100]')
  142. g_plot('set ytics 0, 10')
  143. g_plot('set title "{} : loads : CPU {:0>3} : {:%F %H:%M}"'.format(testname, cpu_index, datetime.now()))
  144. g_plot('set ylabel "CPU load (percent)"')
  145. # override common
  146. g_plot('set key off')
  147. set_4_plot_linestyles(g_plot)
  148. g_plot('plot "' + file_name + '" using {:d}:{:d} with linespoints linestyle 1 axis x1y1'.format(C_ELAPSED, C_LOAD))
  149. def plot_pstate_cpu_with_sample():
  150. """ Plot all cpu information """
  151. if os.path.exists('cpu.csv'):
  152. output_png = 'all_cpu_pstates_vs_samples.png'
  153. g_plot = common_all_gnuplot_settings(output_png)
  154. g_plot('set yrange [0:40]')
  155. # override common
  156. g_plot('set xlabel "Samples"')
  157. g_plot('set ylabel "P-State"')
  158. g_plot('set title "{} : cpu pstate vs. sample : {:%F %H:%M}"'.format(testname, datetime.now()))
  159. title_list = subprocess.check_output('ls cpu???.csv | sed -e \'s/.csv//\'',shell=True).replace('\n', ' ')
  160. plot_str = "plot for [i in title_list] i.'.csv' using {:d}:{:d} pt 7 ps 1 title i".format(C_SAMPLE, C_TO)
  161. g_plot('title_list = "{}"'.format(title_list))
  162. g_plot(plot_str)
  163. def plot_pstate_cpu():
  164. """ Plot all cpu information from csv files """
  165. output_png = 'all_cpu_pstates.png'
  166. g_plot = common_all_gnuplot_settings(output_png)
  167. g_plot('set yrange [0:40]')
  168. g_plot('set ylabel "P-State"')
  169. g_plot('set title "{} : cpu pstates : {:%F %H:%M}"'.format(testname, datetime.now()))
  170. # the following command is really cool, but doesn't work with the CPU masking option because it aborts on the first missing file.
  171. # plot_str = 'plot for [i=0:*] file=sprintf("cpu%03d.csv",i) title_s=sprintf("cpu%03d",i) file using 16:7 pt 7 ps 1 title title_s'
  172. #
  173. title_list = subprocess.check_output('ls cpu???.csv | sed -e \'s/.csv//\'',shell=True).replace('\n', ' ')
  174. plot_str = "plot for [i in title_list] i.'.csv' using {:d}:{:d} pt 7 ps 1 title i".format(C_ELAPSED, C_TO)
  175. g_plot('title_list = "{}"'.format(title_list))
  176. g_plot(plot_str)
  177. def plot_load_cpu():
  178. """ Plot all cpu loads """
  179. output_png = 'all_cpu_loads.png'
  180. g_plot = common_all_gnuplot_settings(output_png)
  181. g_plot('set yrange [0:100]')
  182. g_plot('set ylabel "CPU load (percent)"')
  183. g_plot('set title "{} : cpu loads : {:%F %H:%M}"'.format(testname, datetime.now()))
  184. title_list = subprocess.check_output('ls cpu???.csv | sed -e \'s/.csv//\'',shell=True).replace('\n', ' ')
  185. plot_str = "plot for [i in title_list] i.'.csv' using {:d}:{:d} pt 7 ps 1 title i".format(C_ELAPSED, C_LOAD)
  186. g_plot('title_list = "{}"'.format(title_list))
  187. g_plot(plot_str)
  188. def plot_frequency_cpu():
  189. """ Plot all cpu frequencies """
  190. output_png = 'all_cpu_frequencies.png'
  191. g_plot = common_all_gnuplot_settings(output_png)
  192. g_plot('set yrange [0:4]')
  193. g_plot('set ylabel "CPU Frequency (GHz)"')
  194. g_plot('set title "{} : cpu frequencies : {:%F %H:%M}"'.format(testname, datetime.now()))
  195. title_list = subprocess.check_output('ls cpu???.csv | sed -e \'s/.csv//\'',shell=True).replace('\n', ' ')
  196. plot_str = "plot for [i in title_list] i.'.csv' using {:d}:{:d} pt 7 ps 1 title i".format(C_ELAPSED, C_FREQ)
  197. g_plot('title_list = "{}"'.format(title_list))
  198. g_plot(plot_str)
  199. def plot_duration_cpu():
  200. """ Plot all cpu durations """
  201. output_png = 'all_cpu_durations.png'
  202. g_plot = common_all_gnuplot_settings(output_png)
  203. g_plot('set yrange [0:5000]')
  204. g_plot('set ytics 0, 500')
  205. g_plot('set ylabel "Timer Duration (MilliSeconds)"')
  206. g_plot('set title "{} : cpu durations : {:%F %H:%M}"'.format(testname, datetime.now()))
  207. title_list = subprocess.check_output('ls cpu???.csv | sed -e \'s/.csv//\'',shell=True).replace('\n', ' ')
  208. plot_str = "plot for [i in title_list] i.'.csv' using {:d}:{:d} pt 7 ps 1 title i".format(C_ELAPSED, C_DURATION)
  209. g_plot('title_list = "{}"'.format(title_list))
  210. g_plot(plot_str)
  211. def plot_scaled_cpu():
  212. """ Plot all cpu scaled busy """
  213. output_png = 'all_cpu_scaled.png'
  214. g_plot = common_all_gnuplot_settings(output_png)
  215. # autoscale this one, no set y range
  216. g_plot('set ylabel "Scaled Busy (Unitless)"')
  217. g_plot('set title "{} : cpu scaled busy : {:%F %H:%M}"'.format(testname, datetime.now()))
  218. title_list = subprocess.check_output('ls cpu???.csv | sed -e \'s/.csv//\'',shell=True).replace('\n', ' ')
  219. plot_str = "plot for [i in title_list] i.'.csv' using {:d}:{:d} pt 7 ps 1 title i".format(C_ELAPSED, C_SCALED)
  220. g_plot('title_list = "{}"'.format(title_list))
  221. g_plot(plot_str)
  222. def plot_boost_cpu():
  223. """ Plot all cpu IO Boosts """
  224. output_png = 'all_cpu_boost.png'
  225. g_plot = common_all_gnuplot_settings(output_png)
  226. g_plot('set yrange [0:100]')
  227. g_plot('set ylabel "CPU IO Boost (percent)"')
  228. g_plot('set title "{} : cpu io boost : {:%F %H:%M}"'.format(testname, datetime.now()))
  229. title_list = subprocess.check_output('ls cpu???.csv | sed -e \'s/.csv//\'',shell=True).replace('\n', ' ')
  230. plot_str = "plot for [i in title_list] i.'.csv' using {:d}:{:d} pt 7 ps 1 title i".format(C_ELAPSED, C_BOOST)
  231. g_plot('title_list = "{}"'.format(title_list))
  232. g_plot(plot_str)
  233. def plot_ghz_cpu():
  234. """ Plot all cpu tsc ghz """
  235. output_png = 'all_cpu_ghz.png'
  236. g_plot = common_all_gnuplot_settings(output_png)
  237. # autoscale this one, no set y range
  238. g_plot('set ylabel "TSC Frequency (GHz)"')
  239. g_plot('set title "{} : cpu TSC Frequencies (Sanity check calculation) : {:%F %H:%M}"'.format(testname, datetime.now()))
  240. title_list = subprocess.check_output('ls cpu???.csv | sed -e \'s/.csv//\'',shell=True).replace('\n', ' ')
  241. plot_str = "plot for [i in title_list] i.'.csv' using {:d}:{:d} pt 7 ps 1 title i".format(C_ELAPSED, C_GHZ)
  242. g_plot('title_list = "{}"'.format(title_list))
  243. g_plot(plot_str)
  244. def common_all_gnuplot_settings(output_png):
  245. """ common gnuplot settings for multiple CPUs one one graph. """
  246. g_plot = common_gnuplot_settings()
  247. g_plot('set output "' + output_png + '"')
  248. return(g_plot)
  249. def common_gnuplot_settings():
  250. """ common gnuplot settings. """
  251. g_plot = Gnuplot.Gnuplot(persist=1)
  252. # The following line is for rigor only. It seems to be assumed for .csv files
  253. g_plot('set datafile separator \",\"')
  254. g_plot('set ytics nomirror')
  255. g_plot('set xtics nomirror')
  256. g_plot('set xtics font ", 10"')
  257. g_plot('set ytics font ", 10"')
  258. g_plot('set tics out scale 1.0')
  259. g_plot('set grid')
  260. g_plot('set key out horiz')
  261. g_plot('set key bot center')
  262. g_plot('set key samplen 2 spacing .8 font ", 9"')
  263. g_plot('set term png size 1200, 600')
  264. g_plot('set title font ", 11"')
  265. g_plot('set ylabel font ", 10"')
  266. g_plot('set xlabel font ", 10"')
  267. g_plot('set xlabel offset 0, 0.5')
  268. g_plot('set xlabel "Elapsed Time (Seconds)"')
  269. return(g_plot)
  270. def set_4_plot_linestyles(g_plot):
  271. """ set the linestyles used for 4 plots in 1 graphs. """
  272. g_plot('set style line 1 linetype 1 linecolor rgb "green" pointtype -1')
  273. g_plot('set style line 2 linetype 1 linecolor rgb "red" pointtype -1')
  274. g_plot('set style line 3 linetype 1 linecolor rgb "purple" pointtype -1')
  275. g_plot('set style line 4 linetype 1 linecolor rgb "blue" pointtype -1')
  276. def store_csv(cpu_int, time_pre_dec, time_post_dec, core_busy, scaled, _from, _to, mperf, aperf, tsc, freq_ghz, io_boost, common_comm, load, duration_ms, sample_num, elapsed_time, tsc_ghz):
  277. """ Store master csv file information """
  278. global graph_data_present
  279. if cpu_mask[cpu_int] == 0:
  280. return
  281. try:
  282. f_handle = open('cpu.csv', 'a')
  283. string_buffer = "CPU_%03u, %05u, %06u, %u, %u, %u, %u, %u, %u, %u, %.4f, %u, %.2f, %.3f, %u, %.3f, %.3f, %s\n" % (cpu_int, int(time_pre_dec), int(time_post_dec), int(core_busy), int(scaled), int(_from), int(_to), int(mperf), int(aperf), int(tsc), freq_ghz, int(io_boost), load, duration_ms, sample_num, elapsed_time, tsc_ghz, common_comm)
  284. f_handle.write(string_buffer);
  285. f_handle.close()
  286. except:
  287. print('IO error cpu.csv')
  288. return
  289. graph_data_present = True;
  290. def split_csv():
  291. """ seperate the all csv file into per CPU csv files. """
  292. global current_max_cpu
  293. if os.path.exists('cpu.csv'):
  294. for index in range(0, current_max_cpu + 1):
  295. if cpu_mask[int(index)] != 0:
  296. os.system('grep -m 1 common_cpu cpu.csv > cpu{:0>3}.csv'.format(index))
  297. os.system('grep CPU_{:0>3} cpu.csv >> cpu{:0>3}.csv'.format(index, index))
  298. def fix_ownership(path):
  299. """Change the owner of the file to SUDO_UID, if required"""
  300. uid = os.environ.get('SUDO_UID')
  301. gid = os.environ.get('SUDO_GID')
  302. if uid is not None:
  303. os.chown(path, int(uid), int(gid))
  304. def cleanup_data_files():
  305. """ clean up existing data files """
  306. if os.path.exists('cpu.csv'):
  307. os.remove('cpu.csv')
  308. f_handle = open('cpu.csv', 'a')
  309. f_handle.write('common_cpu, common_secs, common_usecs, core_busy, scaled_busy, from, to, mperf, aperf, tsc, freq, boost, load, duration_ms, sample_num, elapsed_time, tsc_ghz, common_comm')
  310. f_handle.write('\n')
  311. f_handle.close()
  312. def clear_trace_file():
  313. """ Clear trace file """
  314. try:
  315. f_handle = open('/sys/kernel/debug/tracing/trace', 'w')
  316. f_handle.close()
  317. except:
  318. print('IO error clearing trace file ')
  319. quit()
  320. def enable_trace():
  321. """ Enable trace """
  322. try:
  323. open('/sys/kernel/debug/tracing/events/power/pstate_sample/enable'
  324. , 'w').write("1")
  325. except:
  326. print('IO error enabling trace ')
  327. quit()
  328. def disable_trace():
  329. """ Disable trace """
  330. try:
  331. open('/sys/kernel/debug/tracing/events/power/pstate_sample/enable'
  332. , 'w').write("0")
  333. except:
  334. print('IO error disabling trace ')
  335. quit()
  336. def set_trace_buffer_size():
  337. """ Set trace buffer size """
  338. try:
  339. open('/sys/kernel/debug/tracing/buffer_size_kb'
  340. , 'w').write("10240")
  341. except:
  342. print('IO error setting trace buffer size ')
  343. quit()
  344. def free_trace_buffer():
  345. """ Free the trace buffer memory """
  346. try:
  347. open('/sys/kernel/debug/tracing/buffer_size_kb'
  348. , 'w').write("1")
  349. except:
  350. print('IO error setting trace buffer size ')
  351. quit()
  352. def read_trace_data(filename):
  353. """ Read and parse trace data """
  354. global current_max_cpu
  355. global sample_num, last_sec_cpu, last_usec_cpu, start_time
  356. try:
  357. data = open(filename, 'r').read()
  358. except:
  359. print('Error opening ', filename)
  360. quit()
  361. for line in data.splitlines():
  362. search_obj = \
  363. re.search(r'(^(.*?)\[)((\d+)[^\]])(.*?)(\d+)([.])(\d+)(.*?core_busy=)(\d+)(.*?scaled=)(\d+)(.*?from=)(\d+)(.*?to=)(\d+)(.*?mperf=)(\d+)(.*?aperf=)(\d+)(.*?tsc=)(\d+)(.*?freq=)(\d+)'
  364. , line)
  365. if search_obj:
  366. cpu = search_obj.group(3)
  367. cpu_int = int(cpu)
  368. cpu = str(cpu_int)
  369. time_pre_dec = search_obj.group(6)
  370. time_post_dec = search_obj.group(8)
  371. core_busy = search_obj.group(10)
  372. scaled = search_obj.group(12)
  373. _from = search_obj.group(14)
  374. _to = search_obj.group(16)
  375. mperf = search_obj.group(18)
  376. aperf = search_obj.group(20)
  377. tsc = search_obj.group(22)
  378. freq = search_obj.group(24)
  379. common_comm = search_obj.group(2).replace(' ', '')
  380. # Not all kernel versions have io_boost field
  381. io_boost = '0'
  382. search_obj = re.search(r'.*?io_boost=(\d+)', line)
  383. if search_obj:
  384. io_boost = search_obj.group(1)
  385. if sample_num == 0 :
  386. start_time = Decimal(time_pre_dec) + Decimal(time_post_dec) / Decimal(1000000)
  387. sample_num += 1
  388. if last_sec_cpu[cpu_int] == 0 :
  389. last_sec_cpu[cpu_int] = time_pre_dec
  390. last_usec_cpu[cpu_int] = time_post_dec
  391. else :
  392. duration_us = (int(time_pre_dec) - int(last_sec_cpu[cpu_int])) * 1000000 + (int(time_post_dec) - int(last_usec_cpu[cpu_int]))
  393. duration_ms = Decimal(duration_us) / Decimal(1000)
  394. last_sec_cpu[cpu_int] = time_pre_dec
  395. last_usec_cpu[cpu_int] = time_post_dec
  396. elapsed_time = Decimal(time_pre_dec) + Decimal(time_post_dec) / Decimal(1000000) - start_time
  397. load = Decimal(int(mperf)*100)/ Decimal(tsc)
  398. freq_ghz = Decimal(freq)/Decimal(1000000)
  399. # Sanity check calculation, typically anomalies indicate missed samples
  400. # However, check for 0 (should never occur)
  401. tsc_ghz = Decimal(0)
  402. if duration_ms != Decimal(0) :
  403. tsc_ghz = Decimal(tsc)/duration_ms/Decimal(1000000)
  404. store_csv(cpu_int, time_pre_dec, time_post_dec, core_busy, scaled, _from, _to, mperf, aperf, tsc, freq_ghz, io_boost, common_comm, load, duration_ms, sample_num, elapsed_time, tsc_ghz)
  405. if cpu_int > current_max_cpu:
  406. current_max_cpu = cpu_int
  407. # End of for each trace line loop
  408. # Now seperate the main overall csv file into per CPU csv files.
  409. split_csv()
  410. interval = ""
  411. filename = ""
  412. cpu_list = ""
  413. testname = ""
  414. graph_data_present = False;
  415. valid1 = False
  416. valid2 = False
  417. cpu_mask = zeros((MAX_CPUS,), dtype=int)
  418. try:
  419. opts, args = getopt.getopt(sys.argv[1:],"ht:i:c:n:",["help","trace_file=","interval=","cpu=","name="])
  420. except getopt.GetoptError:
  421. print_help()
  422. sys.exit(2)
  423. for opt, arg in opts:
  424. if opt == '-h':
  425. print()
  426. sys.exit()
  427. elif opt in ("-t", "--trace_file"):
  428. valid1 = True
  429. location = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
  430. filename = os.path.join(location, arg)
  431. elif opt in ("-i", "--interval"):
  432. valid1 = True
  433. interval = arg
  434. elif opt in ("-c", "--cpu"):
  435. cpu_list = arg
  436. elif opt in ("-n", "--name"):
  437. valid2 = True
  438. testname = arg
  439. if not (valid1 and valid2):
  440. print_help()
  441. sys.exit()
  442. if cpu_list:
  443. for p in re.split("[,]", cpu_list):
  444. if int(p) < MAX_CPUS :
  445. cpu_mask[int(p)] = 1
  446. else:
  447. for i in range (0, MAX_CPUS):
  448. cpu_mask[i] = 1
  449. if not os.path.exists('results'):
  450. os.mkdir('results')
  451. # The regular user needs to own the directory, not root.
  452. fix_ownership('results')
  453. os.chdir('results')
  454. if os.path.exists(testname):
  455. print('The test name directory already exists. Please provide a unique test name. Test re-run not supported, yet.')
  456. sys.exit()
  457. os.mkdir(testname)
  458. # The regular user needs to own the directory, not root.
  459. fix_ownership(testname)
  460. os.chdir(testname)
  461. # Temporary (or perhaps not)
  462. cur_version = sys.version_info
  463. print('python version (should be >= 2.7):')
  464. print(cur_version)
  465. # Left as "cleanup" for potential future re-run ability.
  466. cleanup_data_files()
  467. if interval:
  468. filename = "/sys/kernel/debug/tracing/trace"
  469. clear_trace_file()
  470. set_trace_buffer_size()
  471. enable_trace()
  472. print('Sleeping for ', interval, 'seconds')
  473. time.sleep(int(interval))
  474. disable_trace()
  475. current_max_cpu = 0
  476. read_trace_data(filename)
  477. if graph_data_present == False:
  478. print('No valid data to plot')
  479. sys.exit(2)
  480. for cpu_no in range(0, current_max_cpu + 1):
  481. plot_perf_busy_with_sample(cpu_no)
  482. plot_perf_busy(cpu_no)
  483. plot_durations(cpu_no)
  484. plot_loads(cpu_no)
  485. plot_pstate_cpu_with_sample()
  486. plot_pstate_cpu()
  487. plot_load_cpu()
  488. plot_frequency_cpu()
  489. plot_duration_cpu()
  490. plot_scaled_cpu()
  491. plot_boost_cpu()
  492. plot_ghz_cpu()
  493. # It is preferrable, but not necessary, that the regular user owns the files, not root.
  494. for root, dirs, files in os.walk('.'):
  495. for f in files:
  496. fix_ownership(f)
  497. clear_trace_file()
  498. # Free the memory
  499. if interval:
  500. free_trace_buffer()
  501. os.chdir('../../')