Debian Codegraph @

tools/profile_python

raw
1 #!/bin/bash
2 #
3 # A little helper to profile Python scripts and directly python code
4 #
5 #
6
7 set -ue
8
9 mktemp_() {
10 mktemp "${TMPDIR:-/tmp}/profile_pythonXXXXXX"
11 }
12
13 help() {
14 cat << EOF
15 Helper to create profile graphs for Python scripts and code (via -c argument)
16
17 $0 [--help] [--copyq] [-p|--prefix PREFIX] [-c "python code"|script] [ARGS]
18
19 If copyq is available, will also copy to its clipboard while you are enjoying
20 the view.
21
22 If script file is not found, will try to locate it in the PATH, and proceed with
23 it if found.
24 EOF
25 exit 0
26 }
27
28 [ "$#" = 0 ] && help
29
30 prefix=
31 copyq=
32
33 while [[ "$#" -gt 0 ]]; do case "$1" in
34 -h|--help)
35 help;;
36 -c)
37 echo "We are passed Python statement to profile."
38 shift
39 prefix=$(mktemp_)
40 pyfile="$prefix.py"
41 echo "$1" >| "$pyfile"
42 shift
43 #echo "Temporary script $pyfile will be removed after"
44 #trap "rm -f ${prefix}*" 0
45 break
46 ;;
47 -p|--prefix)
48 shift
49 prefix="$1"
50 echo "Prefix $prefix"
51 shift
52 ;;
53 --copyq)
54 shift
55 hash copyq 2>/dev/null || { echo "No copyq found"; exit 1; }
56 copyq=yes
57 ;;
58 *) # must be a script
59 pyfile="$1"
60 shift
61 break
62 ;;
63 esac; done
64
65
66 if [ -z "$prefix" ]; then
67 prefix=$(mktemp_ profile_pythonXXXXXX)
68 fi
69
70 pstatsfile="$prefix.pstats"
71 pngfile="$prefix.png"
72 statsfile="$prefix.stats"
73
74 if [ ! -e "$pyfile" ]; then
75 echo "File $pyfile is not found. Is it a script in the PATH?"
76 pyfile_=$(command -v "$pyfile" 2>/dev/null)
77 if [ -n "$pyfile_" ]; then
78 echo " Found $pyfile_ which we will use instead"
79 pyfile="$pyfile_"
80 else
81 echo " No file found. Exiting"
82 exit 1
83 fi
84 fi
85
86 echo "Profiling $pyfile"
87 python -m cProfile -s name -o "$pstatsfile" "$pyfile" "$@" || echo "E: Exited with $?"
88 gprof2dot -f pstats "$pstatsfile" | dot -Tpng -o "$pngfile"
89
90 echo "Stats file $statsfile"
91 python -c "import pstats; pstats.Stats('$pstatsfile').sort_stats(pstats.SortKey.CUMULATIVE).print_stats()" >| "$statsfile"
92 head -n 20 "$statsfile"
93
94 echo "Showing $pngfile"
95 xdg-open "$pngfile" &
96
97 if [ -n "$copyq" ]; then
98 echo "Copying $statsfile to CopyQ clipboard"
99 copyq write text/plain - < "$statsfile" && copyq select 0
100
101 echo "Copying $pngfile to CopyQ clipboard"
102 copyq write image/png - < "$pngfile" && copyq select 0
103 fi