mirror of
https://github.com/apisnetworks/pyenv.git
synced 2026-11-30 19:59:01 +00:00
Add profiling tools to codebase
This commit is contained in:
1 parent
26de18044d
commit
4837971469
3 files changed
+763
No files matched your search
@@ -0,0 +1,414 @@
|
||||
#!/usr/bin/env zsh
|
||||
# bench.sh — benchmark pyenv shell init time
|
||||
#
|
||||
# Usage:
|
||||
# ./bench/bench.sh # compare upstream/ vs working/, 20 iterations
|
||||
# ./bench/bench.sh -n 50 # 50 iterations
|
||||
# ./bench/bench.sh -s upstream # only benchmark upstream/
|
||||
# ./bench/bench.sh --shell bash # use bash instead of zsh
|
||||
# ./bench/bench.sh --no-rehash # pass --no-rehash to pyenv init
|
||||
# ./bench/bench.sh --count-forks # count subprocess spawns instead of timing
|
||||
#
|
||||
# What it measures:
|
||||
# The full cost of `eval "$(pyenv init - <shell>)"` — both the code generation
|
||||
# subprocess (pyenv init) and the eval execution (PATH dedup, rehash, etc).
|
||||
# Time is measured inside the spawned shell to exclude shell startup overhead.
|
||||
#
|
||||
# Writes results to bench/results/ with a timestamp.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
# ── defaults ──────────────────────────────────────────────────────────
|
||||
ITERATIONS=20
|
||||
TARGETS=(upstream working)
|
||||
BENCH_SHELL=zsh
|
||||
PYENV_INIT_FLAGS=""
|
||||
COUNT_FORKS=0
|
||||
SCRIPT_DIR="${0:A:h}"
|
||||
REPO_DIR="${SCRIPT_DIR:h}"
|
||||
RESULTS_DIR="${SCRIPT_DIR}/results"
|
||||
|
||||
# ── parse args ────────────────────────────────────────────────────────
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
-n) ITERATIONS="$2"; shift 2 ;;
|
||||
-s) if [[ "${TARGETS_SET:-}" != 1 ]]; then TARGETS=(); TARGETS_SET=1; fi
|
||||
TARGETS+=("$2"); shift 2 ;;
|
||||
--shell) BENCH_SHELL="$2"; shift 2 ;;
|
||||
--no-rehash) PYENV_INIT_FLAGS="--no-rehash"; shift ;;
|
||||
--flags) PYENV_INIT_FLAGS="$2"; shift 2 ;;
|
||||
--count-forks) COUNT_FORKS=1; shift ;;
|
||||
-h|--help)
|
||||
sed -n '2,/^$/s/^# //p' "$0"
|
||||
exit 0
|
||||
;;
|
||||
*) echo "Unknown option: $1" >&2; exit 1 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# ── helpers ───────────────────────────────────────────────────────────
|
||||
|
||||
# Median of a sorted array (passed as arguments)
|
||||
median() {
|
||||
local -a vals=("$@")
|
||||
local n=${#vals[@]}
|
||||
local mid=$(( n / 2 ))
|
||||
if (( n % 2 == 1 )); then
|
||||
printf '%s' "${vals[$((mid + 1))]}"
|
||||
else
|
||||
printf '%s' "$(( (${vals[$mid]} + ${vals[$((mid + 1))]}) / 2 ))"
|
||||
fi
|
||||
}
|
||||
|
||||
# p95 of a sorted array
|
||||
p95() {
|
||||
local -a vals=("$@")
|
||||
local n=${#vals[@]}
|
||||
local idx=$(( (n * 95 + 99) / 100 ))
|
||||
(( idx > n )) && idx=$n
|
||||
printf '%s' "${vals[$idx]}"
|
||||
}
|
||||
|
||||
# Format microseconds as milliseconds with 1 decimal
|
||||
fmt_ms() {
|
||||
local us="$1"
|
||||
local ms_int=$(( us / 1000 ))
|
||||
local ms_frac=$(( (us % 1000) / 100 ))
|
||||
printf '%d.%d ms' "$ms_int" "$ms_frac"
|
||||
}
|
||||
|
||||
# Shell-appropriate flag to skip rc files (isolate measurement from user config)
|
||||
norc_flag() {
|
||||
case "$1" in
|
||||
zsh) echo "--no-rcs" ;;
|
||||
bash) echo "--norc" ;;
|
||||
*) echo "--norc" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Ensure the results directory exists
|
||||
mkdir -p "$RESULTS_DIR"
|
||||
|
||||
# ── build bench command ───────────────────────────────────────────────
|
||||
|
||||
# Build the shell command that runs `eval "$(pyenv init - <shell>)"` and
|
||||
# measures elapsed time. We measure *inside* the spawned shell to exclude
|
||||
# the shell's own startup overhead.
|
||||
make_bench_cmd() {
|
||||
local pyenv_root="$1"
|
||||
local init_flags="$2"
|
||||
local shell="$3"
|
||||
|
||||
if [[ "$shell" == "zsh" ]]; then
|
||||
# zsh has $EPOCHREALTIME (microsecond precision, no forks)
|
||||
cat <<EOZCMD
|
||||
zmodload zsh/datetime
|
||||
local _t0=\$EPOCHREALTIME
|
||||
export PYENV_ROOT="$pyenv_root"
|
||||
export PATH="$pyenv_root/bin:\$PATH"
|
||||
eval "\$(pyenv init - zsh $init_flags)"
|
||||
local _t1=\$EPOCHREALTIME
|
||||
printf '%d' "\$(( (\$_t1 - \$_t0) * 1000000 ))"
|
||||
EOZCMD
|
||||
else
|
||||
# macOS bash 3.2 lacks EPOCHREALTIME; use python3 for sub-ms timing
|
||||
cat <<EOBCMD
|
||||
_t0=\$(python3 -c 'import time; print(int(time.time()*1000000))')
|
||||
export PYENV_ROOT="$pyenv_root"
|
||||
export PATH="$pyenv_root/bin:\$PATH"
|
||||
eval "\$(pyenv init - bash $init_flags)"
|
||||
_t1=\$(python3 -c 'import time; print(int(time.time()*1000000))')
|
||||
printf '%d' "\$(( _t1 - _t0 ))"
|
||||
EOBCMD
|
||||
fi
|
||||
}
|
||||
|
||||
# ── fork counting ─────────────────────────────────────────────────────
|
||||
|
||||
# pyenv's architecture makes fork counting harder than nvm: each libexec
|
||||
# script is a separate bash process invoked via exec. PYENV_DEBUG=1 sets
|
||||
# `set -x` in every script, so xtrace spans all pyenv-internal processes.
|
||||
# But subprocesses like `sort`, `bash --norc`, etc. don't produce xtrace.
|
||||
#
|
||||
# Strategy: combine PYENV_DEBUG xtrace (to see which scripts invoke what)
|
||||
# with direct grep for known external command patterns in the trace output.
|
||||
|
||||
make_fork_cmd() {
|
||||
local pyenv_root="$1"
|
||||
local init_flags="$2"
|
||||
local shell="$3"
|
||||
|
||||
cat <<EOFCMD
|
||||
export PYENV_ROOT="$pyenv_root"
|
||||
export PATH="$pyenv_root/bin:\$PATH"
|
||||
export PYENV_DEBUG=1
|
||||
eval "\$(pyenv init - $shell $init_flags)"
|
||||
EOFCMD
|
||||
}
|
||||
|
||||
# Count subprocess-spawning patterns in xtrace output.
|
||||
# This catches: exec, command substitution $(), pipes to external commands.
|
||||
# It's a lower bound — some forks are invisible to xtrace.
|
||||
count_forks_in_trace() {
|
||||
local trace_file="$1"
|
||||
|
||||
# Known external commands that pyenv invokes during init
|
||||
local FORK_CMDS='(sort|uniq|bash|cat|sed|diff|cp|rm|mkdir|mktemp|sleep|readlink|pyenv|pyenv-commands|pyenv-init|pyenv-rehash|pyenv-versions|pyenv-hooks)'
|
||||
|
||||
local count
|
||||
count=$(grep -oE "(^|\s)${FORK_CMDS}(\s|$)" "$trace_file" \
|
||||
| awk '{$1=$1}1' \
|
||||
| grep -cE "^${FORK_CMDS}$" 2>/dev/null) || count=0
|
||||
echo "$count"
|
||||
}
|
||||
|
||||
# Breakdown of which commands were forked and how many times.
|
||||
fork_breakdown() {
|
||||
local trace_file="$1"
|
||||
local FORK_CMDS='(sort|uniq|bash|cat|sed|diff|cp|rm|mkdir|mktemp|sleep|readlink|pyenv|pyenv-commands|pyenv-init|pyenv-rehash|pyenv-versions|pyenv-hooks)'
|
||||
|
||||
grep -oE "(^|\s)${FORK_CMDS}(\s|$)" "$trace_file" \
|
||||
| awk '{$1=$1}1' \
|
||||
| grep -E "^${FORK_CMDS}$" \
|
||||
| sort | uniq -c | sort -rn \
|
||||
| head -20
|
||||
}
|
||||
|
||||
# A more reliable approach: count unique process spawns by looking for
|
||||
# shebang invocations and exec patterns in the PYENV_DEBUG trace.
|
||||
# Each `+(filename:line): ` prefix with a *different* filename indicates
|
||||
# a new bash process.
|
||||
count_script_invocations() {
|
||||
local trace_file="$1"
|
||||
# Extract unique script filenames from xtrace prefixes
|
||||
# Format: +(path/to/script:line): ...
|
||||
grep -oE '\+\([^:]+:' "$trace_file" \
|
||||
| sed 's/^+(//' | sed 's/:$//' \
|
||||
| sort -u
|
||||
}
|
||||
|
||||
# Run fork counting mode
|
||||
count_forks() {
|
||||
echo "pyenv-tune fork count"
|
||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||
echo "shell: $BENCH_SHELL"
|
||||
echo "flags: ${PYENV_INIT_FLAGS:-"(none — default init)"}"
|
||||
echo "targets: ${TARGETS[*]}"
|
||||
echo ""
|
||||
|
||||
local ts="$(date +%Y%m%d-%H%M%S)"
|
||||
local results_file="${RESULTS_DIR}/${ts}-forks.txt"
|
||||
|
||||
{
|
||||
echo "pyenv-tune fork count — $(date)"
|
||||
echo "shell: $BENCH_SHELL | flags: ${PYENV_INIT_FLAGS:-"(default)"}"
|
||||
echo "note: lower bound — not all forks are visible to xtrace"
|
||||
echo ""
|
||||
} > "$results_file"
|
||||
|
||||
local pyenv_root fork_cmd trace_file
|
||||
|
||||
for target in "${TARGETS[@]}"; do
|
||||
pyenv_root="${REPO_DIR}/${target}"
|
||||
|
||||
if [[ ! -d "${pyenv_root}/libexec" ]]; then
|
||||
echo "ERROR: ${pyenv_root}/libexec not found — is this a pyenv checkout?" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "▸ Counting forks: ${target}/"
|
||||
|
||||
fork_cmd="$(make_fork_cmd "$pyenv_root" "$PYENV_INIT_FLAGS" "$BENCH_SHELL")"
|
||||
trace_file="$(mktemp)"
|
||||
|
||||
# Run with PYENV_DEBUG, which sets xtrace in all pyenv scripts.
|
||||
# stderr gets the xtrace output from pyenv scripts.
|
||||
# The eval'd shell also inherits PYENV_DEBUG (pyenv exports it).
|
||||
"$BENCH_SHELL" "$(norc_flag "$BENCH_SHELL")" -c "$fork_cmd" > /dev/null 2>"$trace_file"
|
||||
|
||||
echo ""
|
||||
echo " Scripts invoked (each = 1 bash fork):"
|
||||
local scripts
|
||||
scripts="$(count_script_invocations "$trace_file")"
|
||||
local script_count
|
||||
script_count=$(echo "$scripts" | wc -l | tr -d ' ')
|
||||
echo "$scripts" | while read -r s; do
|
||||
echo " · $s"
|
||||
done
|
||||
echo " Total script invocations: $script_count"
|
||||
|
||||
echo ""
|
||||
echo " External command breakdown (from xtrace):"
|
||||
fork_breakdown "$trace_file" | while read -r line; do
|
||||
echo " $line"
|
||||
done
|
||||
|
||||
echo ""
|
||||
|
||||
{
|
||||
echo "${target}/"
|
||||
echo " Scripts invoked:"
|
||||
echo "$scripts" | while read -r s; do
|
||||
echo " $s"
|
||||
done
|
||||
echo " Total script invocations: $script_count"
|
||||
echo ""
|
||||
echo " External command breakdown:"
|
||||
fork_breakdown "$trace_file"
|
||||
echo ""
|
||||
} >> "$results_file"
|
||||
|
||||
rm -f "$trace_file"
|
||||
done
|
||||
|
||||
echo "results saved to: ${results_file}"
|
||||
}
|
||||
|
||||
# ── timing mode ───────────────────────────────────────────────────────
|
||||
|
||||
main() {
|
||||
if (( COUNT_FORKS )); then
|
||||
count_forks
|
||||
return
|
||||
fi
|
||||
|
||||
echo "pyenv-tune bench"
|
||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||
echo "shell: $BENCH_SHELL"
|
||||
echo "iterations: $ITERATIONS"
|
||||
echo "flags: ${PYENV_INIT_FLAGS:-"(none — default init)"}"
|
||||
echo "targets: ${TARGETS[*]}"
|
||||
echo ""
|
||||
|
||||
local ts="$(date +%Y%m%d-%H%M%S)"
|
||||
local results_file="${RESULTS_DIR}/${ts}.txt"
|
||||
|
||||
{
|
||||
echo "pyenv-tune bench — $(date)"
|
||||
echo "shell: $BENCH_SHELL | iterations: $ITERATIONS | flags: ${PYENV_INIT_FLAGS:-"(default)"}"
|
||||
echo ""
|
||||
} > "$results_file"
|
||||
|
||||
declare -A result_min result_med result_p95 result_max result_mean
|
||||
local pyenv_root bench_cmd min max med mean p95_val sum i us t
|
||||
local -a timings
|
||||
|
||||
for target in "${TARGETS[@]}"; do
|
||||
pyenv_root="${REPO_DIR}/${target}"
|
||||
|
||||
if [[ ! -d "${pyenv_root}/libexec" ]]; then
|
||||
echo "ERROR: ${pyenv_root}/libexec not found — is this a pyenv checkout?" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "▸ Benchmarking: ${target}/"
|
||||
echo " warming up..."
|
||||
|
||||
# Warmup (3 runs, discarded — pyenv rehash creates shims on first run)
|
||||
bench_cmd="$(make_bench_cmd "$pyenv_root" "$PYENV_INIT_FLAGS" "$BENCH_SHELL")"
|
||||
for _ in 1 2 3; do
|
||||
"$BENCH_SHELL" "$(norc_flag "$BENCH_SHELL")" -c "$bench_cmd" > /dev/null 2>&1
|
||||
done
|
||||
|
||||
echo " running ${ITERATIONS} iterations..."
|
||||
|
||||
timings=()
|
||||
for i in $(seq 1 "$ITERATIONS"); do
|
||||
us="$("$BENCH_SHELL" "$(norc_flag "$BENCH_SHELL")" -c "$bench_cmd" 2>/dev/null)"
|
||||
timings+=("$us")
|
||||
if (( i % 5 == 0 )); then
|
||||
printf ' %d/%d\n' "$i" "$ITERATIONS"
|
||||
fi
|
||||
done
|
||||
|
||||
# Sort (zsh numeric sort)
|
||||
timings=(${(n)timings})
|
||||
|
||||
# Stats
|
||||
min="${timings[1]}"
|
||||
max="${timings[-1]}"
|
||||
sum=0
|
||||
for t in "${timings[@]}"; do
|
||||
sum=$(( sum + t ))
|
||||
done
|
||||
mean=$(( sum / ${#timings[@]} ))
|
||||
med="$(median "${timings[@]}")"
|
||||
p95_val="$(p95 "${timings[@]}")"
|
||||
|
||||
result_min[$target]="$min"
|
||||
result_med[$target]="$med"
|
||||
result_p95[$target]="$p95_val"
|
||||
result_max[$target]="$max"
|
||||
result_mean[$target]="$mean"
|
||||
|
||||
echo ""
|
||||
echo " ${target}/"
|
||||
echo " min: $(fmt_ms "$min")"
|
||||
echo " median: $(fmt_ms "$med")"
|
||||
echo " mean: $(fmt_ms "$mean")"
|
||||
echo " p95: $(fmt_ms "$p95_val")"
|
||||
echo " max: $(fmt_ms "$max")"
|
||||
echo ""
|
||||
|
||||
{
|
||||
echo "${target}/"
|
||||
echo " min: $(fmt_ms "$min")"
|
||||
echo " median: $(fmt_ms "$med")"
|
||||
echo " mean: $(fmt_ms "$mean")"
|
||||
echo " p95: $(fmt_ms "$p95_val")"
|
||||
echo " max: $(fmt_ms "$max")"
|
||||
echo " raw (µs): ${timings[*]}"
|
||||
echo ""
|
||||
} >> "$results_file"
|
||||
done
|
||||
|
||||
# ── comparison ──────────────────────────────────────────────────────
|
||||
|
||||
if (( ${#TARGETS[@]} == 2 )); then
|
||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||
echo "comparison (median)"
|
||||
|
||||
local a="${TARGETS[1]}" b="${TARGETS[2]}"
|
||||
local a_med="${result_med[$a]}"
|
||||
local b_med="${result_med[$b]}"
|
||||
|
||||
if (( a_med > 0 )); then
|
||||
local diff_us=$(( a_med - b_med ))
|
||||
local abs_diff_us=${diff_us#-}
|
||||
local pct=$(( (abs_diff_us * 100) / a_med ))
|
||||
local label
|
||||
if (( diff_us > 0 )); then
|
||||
label="faster"
|
||||
elif (( diff_us < 0 )); then
|
||||
label="slower"
|
||||
else
|
||||
label="same"
|
||||
fi
|
||||
|
||||
echo " ${a}: $(fmt_ms "$a_med")"
|
||||
echo " ${b}: $(fmt_ms "$b_med")"
|
||||
if [[ "$label" == "same" ]]; then
|
||||
echo " delta: 0 ms (identical)"
|
||||
else
|
||||
echo " delta: $(fmt_ms "$abs_diff_us") ${label} (${pct}%)"
|
||||
fi
|
||||
|
||||
{
|
||||
echo "comparison (median)"
|
||||
echo " ${a}: $(fmt_ms "$a_med")"
|
||||
echo " ${b}: $(fmt_ms "$b_med")"
|
||||
if [[ "$label" == "same" ]]; then
|
||||
echo " delta: 0 ms (identical)"
|
||||
else
|
||||
echo " delta: $(fmt_ms "$abs_diff_us") ${label} (${pct}%)"
|
||||
fi
|
||||
} >> "$results_file"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
fi
|
||||
|
||||
echo "results saved to: ${results_file}"
|
||||
}
|
||||
|
||||
main
|
||||
@@ -0,0 +1,160 @@
|
||||
#!/usr/bin/env bash
|
||||
# make-fixture.sh — create a realistic pyenv versions/ layout for profiling
|
||||
#
|
||||
# Usage:
|
||||
# ./bench/make-fixture.sh <pyenv-root> [--large]
|
||||
#
|
||||
# Creates:
|
||||
# - 3 real Python versions (3.10.0, 3.11.0, 3.12.0) with typical bin/ executables
|
||||
# - 1 alias (symlink from 3 -> 3.12.0, the --skip-aliases case)
|
||||
# - 12 virtualenvs under versions/3.12.0/envs/ (the pyenv-virtualenv layout)
|
||||
# - Each virtualenv gets 15-25 executables (popular packages)
|
||||
#
|
||||
# With --large:
|
||||
# - 6 Python versions
|
||||
# - 30 virtualenvs (10 per version)
|
||||
# - Stress test for native-api's "dozens of virtualenvs" scenario
|
||||
#
|
||||
# Idempotent: removes and recreates the versions/ directory.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
PYENV_ROOT="${1:?Usage: make-fixture.sh <pyenv-root> [--large]}"
|
||||
LARGE=0
|
||||
[[ "${2:-}" == "--large" ]] && LARGE=1
|
||||
|
||||
VERSIONS_DIR="${PYENV_ROOT}/versions"
|
||||
|
||||
# Clean slate
|
||||
rm -rf "$VERSIONS_DIR"
|
||||
mkdir -p "$VERSIONS_DIR"
|
||||
|
||||
# Common Python executables (present in every version)
|
||||
PYTHON_BINS=(
|
||||
python python3 pip pip3 wheel
|
||||
python3-config idle3 pydoc3 2to3
|
||||
easy_install easy_install-3
|
||||
)
|
||||
|
||||
# Additional executables that show up when popular packages are installed
|
||||
VENV_BINS_POOL=(
|
||||
pytest py.test coverage black isort flake8 mypy
|
||||
pylint autopep8 yapf bandit pyflakes pep8
|
||||
ipython jupyter jupyter-notebook jupyter-lab
|
||||
sphinx-build sphinx-quickstart sphinx-apidoc
|
||||
gunicorn uvicorn hypercorn daphne
|
||||
celery flask django-admin
|
||||
pip pip3 python python3 wheel
|
||||
activate activate.csh activate.fish
|
||||
easy_install setuptools
|
||||
chardetect normalizer dulwich
|
||||
tox nox pre-commit
|
||||
)
|
||||
|
||||
# Create a version directory with standard Python bins
|
||||
make_version() {
|
||||
local ver="$1"
|
||||
local dir="${VERSIONS_DIR}/${ver}/bin"
|
||||
mkdir -p "$dir"
|
||||
for bin in "${PYTHON_BINS[@]}"; do
|
||||
touch "$dir/$bin"
|
||||
chmod +x "$dir/$bin"
|
||||
done
|
||||
}
|
||||
|
||||
# Create a virtualenv directory with a subset of bins
|
||||
make_venv() {
|
||||
local parent_ver="$1"
|
||||
local venv_name="$2"
|
||||
local num_bins="$3"
|
||||
local dir="${VERSIONS_DIR}/${parent_ver}/envs/${venv_name}/bin"
|
||||
mkdir -p "$dir"
|
||||
|
||||
# Always include python/pip
|
||||
touch "$dir/python" "$dir/python3" "$dir/pip" "$dir/pip3"
|
||||
chmod +x "$dir/python" "$dir/python3" "$dir/pip" "$dir/pip3"
|
||||
|
||||
# Add random selection from pool
|
||||
local count=0
|
||||
for bin in "${VENV_BINS_POOL[@]}"; do
|
||||
if (( count >= num_bins )); then
|
||||
break
|
||||
fi
|
||||
touch "$dir/$bin"
|
||||
chmod +x "$dir/$bin"
|
||||
count=$((count + 1))
|
||||
done
|
||||
}
|
||||
|
||||
# ── Build the fixture ────────────────────────────────────────────────
|
||||
|
||||
if (( LARGE )); then
|
||||
VERSIONS=(3.9.0 3.10.0 3.10.5 3.11.0 3.11.7 3.12.0)
|
||||
VENVS_PER_VERSION=10
|
||||
else
|
||||
VERSIONS=(3.10.0 3.11.0 3.12.0)
|
||||
VENVS_PER_VERSION=4
|
||||
fi
|
||||
|
||||
for ver in "${VERSIONS[@]}"; do
|
||||
make_version "$ver"
|
||||
done
|
||||
|
||||
# Create alias: "3" -> 3.12.0 (symlink, should be skipped by --skip-aliases)
|
||||
ln -s "3.12.0" "${VERSIONS_DIR}/3"
|
||||
|
||||
# Create an external symlink: "system-link" -> /usr/bin (should NOT be skipped
|
||||
# by --skip-aliases since it points outside versions_dir)
|
||||
mkdir -p "${VERSIONS_DIR}/external-build/bin"
|
||||
for bin in python python3 pip pip3; do
|
||||
touch "${VERSIONS_DIR}/external-build/bin/$bin"
|
||||
chmod +x "${VERSIONS_DIR}/external-build/bin/$bin"
|
||||
done
|
||||
ln -s "${VERSIONS_DIR}/external-build" "${VERSIONS_DIR}/system-linked"
|
||||
|
||||
# Create virtualenvs
|
||||
VENV_NAMES=(
|
||||
myproject web-api data-pipeline ml-training
|
||||
docs-site cli-tool test-runner lint-env
|
||||
notebook jupyter-work analysis viz-dash
|
||||
scraper etl-job monitoring deploy-tools
|
||||
dev staging prod benchmarks
|
||||
experiment-1 experiment-2 experiment-3 experiment-4
|
||||
legacy-app migration-tool compat-layer sdk-dev
|
||||
)
|
||||
|
||||
venv_idx=0
|
||||
for ver in "${VERSIONS[@]}"; do
|
||||
for i in $(seq 1 "$VENVS_PER_VERSION"); do
|
||||
venv_name="${VENV_NAMES[$venv_idx]}"
|
||||
# Vary the number of executables (15-25)
|
||||
num_bins=$(( 15 + (venv_idx % 11) ))
|
||||
make_venv "$ver" "$venv_name" "$num_bins"
|
||||
venv_idx=$((venv_idx + 1))
|
||||
if (( venv_idx >= ${#VENV_NAMES[@]} )); then
|
||||
venv_idx=0
|
||||
fi
|
||||
done
|
||||
|
||||
# Also create symlinks from envs back to versions/ (pyenv-virtualenv does this)
|
||||
for env_dir in "${VERSIONS_DIR}/${ver}/envs/"*/; do
|
||||
[ -d "$env_dir" ] || continue
|
||||
env_name="$(basename "$env_dir")"
|
||||
# pyenv-virtualenv creates: versions/<venv-name> -> versions/<ver>/envs/<venv-name>
|
||||
ln -s "${ver}/envs/${env_name}" "${VERSIONS_DIR}/${env_name}" 2>/dev/null || true
|
||||
done
|
||||
done
|
||||
|
||||
# Summary
|
||||
version_count=$(ls -1d "${VERSIONS_DIR}"/*/ 2>/dev/null | wc -l | tr -d ' ')
|
||||
symlink_count=$(find "${VERSIONS_DIR}" -maxdepth 1 -type l | wc -l | tr -d ' ')
|
||||
real_count=$((version_count - symlink_count))
|
||||
venv_count=$(find "${VERSIONS_DIR}" -path "*/envs/*" -maxdepth 4 -mindepth 4 -type d | wc -l | tr -d ' ')
|
||||
total_bins=$(find "${VERSIONS_DIR}" -path "*/bin/*" -type f | wc -l | tr -d ' ')
|
||||
|
||||
echo "Fixture created in ${VERSIONS_DIR}/"
|
||||
echo " Real versions: ${real_count}"
|
||||
echo " Aliases (links): ${symlink_count}"
|
||||
echo " Virtualenvs: ${venv_count}"
|
||||
echo " Total binaries: ${total_bins}"
|
||||
echo " Top-level dirs: ${version_count}"
|
||||
@@ -0,0 +1,189 @@
|
||||
#!/usr/bin/env zsh
|
||||
# profile-rehash.sh — timestamp-annotated xtrace of pyenv-rehash
|
||||
#
|
||||
# Usage:
|
||||
# ./bench/profile-rehash.sh <pyenv-root>
|
||||
#
|
||||
# Runs pyenv-rehash with PYENV_DEBUG=1, pipes xtrace through perl to
|
||||
# prepend microsecond timestamps, then produces:
|
||||
# 1. Raw timestamped trace (for inspection)
|
||||
# 2. Summary: top time-consuming gaps between consecutive lines
|
||||
# 3. Phase breakdown: time spent in each logical section
|
||||
#
|
||||
# Requires: perl (with Time::HiRes), bash 3.2+
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
PYENV_ROOT="${1:?Usage: profile-rehash.sh <pyenv-root>}"
|
||||
SCRIPT_DIR="${0:A:h}"
|
||||
RESULTS_DIR="${SCRIPT_DIR}/results"
|
||||
mkdir -p "$RESULTS_DIR"
|
||||
|
||||
TS="$(date +%Y%m%d-%H%M%S)"
|
||||
RAW_TRACE="${RESULTS_DIR}/${TS}-profile-raw.txt"
|
||||
SUMMARY="${RESULTS_DIR}/${TS}-profile-summary.txt"
|
||||
|
||||
echo "Profiling pyenv-rehash in ${PYENV_ROOT}/"
|
||||
|
||||
# ── Clean up shims from prior runs ──────────────────────────────────
|
||||
rm -rf "${PYENV_ROOT}/shims"
|
||||
mkdir -p "${PYENV_ROOT}/shims"
|
||||
|
||||
# ── Run rehash with xtrace, timestamp each line ─────────────────────
|
||||
#
|
||||
# PYENV_DEBUG=1 sets `set -x` in every pyenv script.
|
||||
# Bash 3.2 sends xtrace to stderr. We pipe stderr through perl
|
||||
# which prepends a microsecond timestamp to each line.
|
||||
#
|
||||
# The 2>&1 trick: run bash with stderr redirected to a pipe, then
|
||||
# perl timestamps each line.
|
||||
|
||||
export PYENV_ROOT
|
||||
export PATH="${PYENV_ROOT}/bin:${PYENV_ROOT}/libexec:$PATH"
|
||||
|
||||
# We need to capture stderr (xtrace) separately from stdout.
|
||||
# Strategy: redirect stderr to fd 3, pipe fd 3 through perl.
|
||||
{
|
||||
PYENV_DEBUG=1 bash "${PYENV_ROOT}/libexec/pyenv-rehash" 2>&1 1>/dev/null
|
||||
} | perl -MTime::HiRes=gettimeofday -ne '
|
||||
my ($s, $us) = gettimeofday();
|
||||
printf "%d.%06d %s", $s, $us, $_;
|
||||
' > "$RAW_TRACE"
|
||||
|
||||
LINES=$(wc -l < "$RAW_TRACE" | tr -d ' ')
|
||||
echo "Captured ${LINES} trace lines"
|
||||
|
||||
# ── Analyze: compute deltas between consecutive lines ───────────────
|
||||
|
||||
perl -e '
|
||||
use strict;
|
||||
use warnings;
|
||||
|
||||
my @lines;
|
||||
my $prev_ts = 0;
|
||||
|
||||
# Read all lines with timestamps
|
||||
open my $fh, "<", $ARGV[0] or die "Cannot open $ARGV[0]: $!";
|
||||
while (<$fh>) {
|
||||
if (/^(\d+\.\d+)\s+(.*)/) {
|
||||
my ($ts, $content) = ($1, $2);
|
||||
my $delta = 0;
|
||||
if ($prev_ts > 0) {
|
||||
$delta = ($ts - $prev_ts) * 1_000_000; # microseconds
|
||||
}
|
||||
push @lines, { ts => $ts, delta => $delta, content => $content, line => $. };
|
||||
$prev_ts = $ts;
|
||||
}
|
||||
}
|
||||
close $fh;
|
||||
|
||||
my $total_lines = scalar @lines;
|
||||
return unless $total_lines > 1;
|
||||
|
||||
my $total_us = ($lines[-1]{ts} - $lines[0]{ts}) * 1_000_000;
|
||||
|
||||
# ── Top 30 gaps ──────────────────────────────────────────────────
|
||||
my @sorted = sort { $b->{delta} <=> $a->{delta} } @lines;
|
||||
|
||||
print "=" x 70, "\n";
|
||||
printf "PYENV-REHASH PROFILE — total: %.1f ms, %d trace lines\n",
|
||||
$total_us / 1000, $total_lines;
|
||||
print "=" x 70, "\n\n";
|
||||
|
||||
print "TOP 30 GAPS (time between consecutive trace lines)\n";
|
||||
print "-" x 70, "\n";
|
||||
printf "%-10s %-6s %s\n", "delta", "line", "trace content";
|
||||
print "-" x 70, "\n";
|
||||
|
||||
my $shown = 0;
|
||||
for my $l (@sorted) {
|
||||
last if $shown >= 30;
|
||||
last if $l->{delta} < 50; # skip sub-50µs gaps
|
||||
printf "%7.0f µs L%-4d %.100s\n",
|
||||
$l->{delta}, $l->{line}, $l->{content};
|
||||
$shown++;
|
||||
}
|
||||
|
||||
# ── Phase breakdown ──────────────────────────────────────────────
|
||||
# Identify phases by looking for key function/command patterns
|
||||
print "\n\n";
|
||||
print "PHASE BREAKDOWN\n";
|
||||
print "-" x 70, "\n";
|
||||
|
||||
my %phases;
|
||||
my $current_phase = "startup";
|
||||
my $phase_start = $lines[0]{ts};
|
||||
|
||||
for my $l (@lines) {
|
||||
my $c = $l->{content};
|
||||
my $new_phase;
|
||||
|
||||
if ($c =~ /create_prototype_shim/) {
|
||||
$new_phase = "create_prototype_shim";
|
||||
} elsif ($c =~ /remove_outdated_shims/) {
|
||||
$new_phase = "remove_outdated_shims";
|
||||
} elsif ($c =~ /list_executable_names|pyenv-versions/) {
|
||||
$new_phase = "list_executable_names";
|
||||
} elsif ($c =~ /make_shims/) {
|
||||
$new_phase = "make_shims";
|
||||
} elsif ($c =~ /pyenv-hooks/) {
|
||||
$new_phase = "hooks";
|
||||
} elsif ($c =~ /install_registered_shims/) {
|
||||
$new_phase = "install_registered_shims";
|
||||
} elsif ($c =~ /remove_stale_shims/) {
|
||||
$new_phase = "remove_stale_shims";
|
||||
}
|
||||
|
||||
if (defined $new_phase && $new_phase ne $current_phase) {
|
||||
my $elapsed = ($l->{ts} - $phase_start) * 1_000_000;
|
||||
$phases{$current_phase} = ($phases{$current_phase} || 0) + $elapsed;
|
||||
$current_phase = $new_phase;
|
||||
$phase_start = $l->{ts};
|
||||
}
|
||||
}
|
||||
# Close last phase
|
||||
my $elapsed = ($lines[-1]{ts} - $phase_start) * 1_000_000;
|
||||
$phases{$current_phase} = ($phases{$current_phase} || 0) + $elapsed;
|
||||
|
||||
# Print phases sorted by time
|
||||
for my $p (sort { $phases{$b} <=> $phases{$a} } keys %phases) {
|
||||
printf " %7.1f ms (%4.1f%%) %s\n",
|
||||
$phases{$p} / 1000,
|
||||
($phases{$p} / $total_us) * 100,
|
||||
$p;
|
||||
}
|
||||
printf "\n %7.1f ms (total)\n", $total_us / 1000;
|
||||
|
||||
# ── External command summary ─────────────────────────────────────
|
||||
print "\n\n";
|
||||
print "EXTERNAL COMMANDS (from xtrace)\n";
|
||||
print "-" x 70, "\n";
|
||||
|
||||
my %cmds;
|
||||
my %cmd_time;
|
||||
for my $l (@lines) {
|
||||
my $c = $l->{content};
|
||||
# Match commands at start of xtrace line (after + markers)
|
||||
if ($c =~ /^\+*\s*([\w\/-]+)(?:\s|$)/) {
|
||||
my $cmd = $1;
|
||||
# Filter to known external commands
|
||||
if ($cmd =~ /^(sort|uniq|bash|cat|sed|diff|cp|rm|mkdir|mktemp|chmod|readlink|realpath|wc|head|tail|printf|echo|read|test|true|false|shopt|local|declare|for|while|if|set|export|eval|source|command|type|enable|pyenv[\w-]*)$/) {
|
||||
if ($cmd =~ /^(sort|uniq|bash|cat|sed|diff|cp|rm|mkdir|mktemp|chmod|readlink|realpath|wc|head|tail|pyenv[\w-]*)$/) {
|
||||
$cmds{$cmd}++;
|
||||
$cmd_time{$cmd} = ($cmd_time{$cmd} || 0) + $l->{delta};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
printf "%-20s %6s %10s\n", "command", "count", "assoc. µs";
|
||||
print "-" x 40, "\n";
|
||||
for my $c (sort { $cmd_time{$b} <=> $cmd_time{$a} } keys %cmds) {
|
||||
printf "%-20s %6d %10.0f\n", $c, $cmds{$c}, $cmd_time{$c};
|
||||
}
|
||||
|
||||
' "$RAW_TRACE" | tee "$SUMMARY"
|
||||
|
||||
echo ""
|
||||
echo "Raw trace: ${RAW_TRACE}"
|
||||
echo "Summary: ${SUMMARY}"
|
||||
Reference in new issue
Block a user