Compare commits

...
3 Commits
Author SHA1 Message Date
krosh b1806cda5e update test result 2026-08-24 05:53:12 +03:00
krosh e7836fdf31 article for asvk 2026-08-21 04:44:49 +03:00
krosh 45033e7f6d perf: measure set benchmarks with user and system time 2026-08-20 13:31:12 +03:00
6 changed files with 502 additions and 188 deletions
+28 -28
View File
@@ -1,3 +1,7 @@
# Результаты APT-RPM тестов
Коэффициент считается как отношение времени базовой реализации к времени проверяемой реализации. Значение больше `1×` означает ускорение, меньше `1×` — замедление.
## original set.c w/out optimizations
функция `decode_set` идёт по пути функций:
@@ -6,15 +10,13 @@
2. `decode_golomb`
3. `decode_delta`
| command | average_seconds | run1_seconds | run2_seconds | run3_seconds | exit_status |
| :-------------------------- | :-------------: | :----------: | :----------: | :----------: | ----------: |
| -s check | 4.217343 | 4.310882 | 4.179343 | 4.161804 | 0 |
| -s autoremove | 4.884413 | 4.876135 | 4.882347 | 4.894757 | 0 |
| -s install rpm-build | 4.634789 | 4.652499 | 4.623077 | 4.628792 | 0 |
| -s install openuds-server | 12.704538 | 12.640266 | 12.975482 | 12.497867 | 0 |
| -s install password-store | 8.560463 | 8.561515 | 8.557596 | 8.562277 | 0 |
| --enable-upgrade -s upgrade | 36.271838 | 35.511443 | 35.908641 | 37.395430 | 100 |
| -s dist-upgrade | 90.550086 | 94.702198 | 92.174160 | 84.773901 | 100 |
| command | user, с | system, с | user+system, с |
| :-------------------------- | -------: | --------: | -------------: |
| `-s check` | 1.320000 | 0.050000 | 1.370000 |
| `-s autoremove` | 1.626667 | 0.050000 | 1.676667 |
| `-s install rpm-build` | 2.913333 | 0.070000 | 2.983333 |
| `-s install openuds-server` | 5.526667 | 0.100000 | 5.626667 |
| `-s install password-store` | 2.940000 | 0.070000 | 3.010000 |
## original set.c
@@ -23,26 +25,24 @@
1. `decode_base62_golomb`
2. `decode_delta`
| command | average_seconds | run1_seconds | run2_seconds | run3_seconds | exit_status |
| :-------------------------- | :-------------: | :----------: | :----------: | :----------: | ----------: |
| -s check | 1.570747 | 1.621496 | 1.545001 | 1.545744 | 0 |
| -s autoremove | 2.294502 | 2.312574 | 2.287133 | 2.283798 | 0 |
| -s install rpm-build | 2.108121 | 2.142784 | 2.093474 | 2.088105 | 0 |
| -s install openuds-server | 8.028098 | 8.147214 | 8.001140 | 7.935940 | 0 |
| -s install password-store | 3.373377 | 3.396943 | 3.361290 | 3.361899 | 0 |
| --enable-upgrade -s upgrade | 33.915979 | 33.895262 | 33.770192 | 34.082484 | 100 |
| -s dist-upgrade | 88.722136 | 95.484250 | 85.808085 | 84.874073 | 100 |
Коэффициенты посчитаны относительно `original set.c w/out optimizations`.
| command | user, с | system, с | user+system, с | коэфф. user | коэфф. user+system |
| :-------------------------- | -------: | --------: | -------------: | ----------: | -----------------: |
| `-s check` | 0.453333 | 0.033333 | 0.486666 | 2.912× | 2.815× |
| `-s autoremove` | 0.763333 | 0.040000 | 0.803333 | 2.131× | 2.087× |
| `-s install rpm-build` | 1.210000 | 0.050000 | 1.260000 | 2.408× | 2.368× |
| `-s install openuds-server` | 3.746667 | 0.080000 | 3.826667 | 1.475× | 1.470× |
| `-s install password-store` | 1.233333 | 0.050000 | 1.283333 | 2.384× | 2.345× |
## set9.c
Переписанная реализация `set.c`
Переписанная реализация `set.c`. Коэффициенты посчитаны относительно `original set.c`.
| command | average_seconds | run1_seconds | run2_seconds | run3_seconds | exit_status |
| :-------------------------- | :-------------: | :----------: | :----------: | :----------: | ----------: |
| -s check | 1.550342 | 1.596307 | 1.532768 | 1.521950 | 0 |
| -s autoremove | 2.200188 | 2.237645 | 2.185378 | 2.177540 | 0 |
| -s install rpm-build | 2.031055 | 2.045757 | 2.023173 | 2.024234 | 0 |
| -s install openuds-server | 7.580058 | 7.572994 | 7.582557 | 7.584622 | 0 |
| -s install password-store | 3.337012 | 3.367696 | 3.309826 | 3.333514 | 0 |
| --enable-upgrade -s upgrade | 31.494775 | 31.535714 | 31.585522 | 31.363090 | 100 |
| -s dist-upgrade | 85.326580 | 85.389775 | 85.604566 | 84.985398 | 100 |
| command | user, с | system, с | user+system, с | коэфф. user | коэфф. user+system |
| :-------------------------- | -------: | --------: | -------------: | ----------: | -----------------: |
| `-s check` | 0.503333 | 0.040000 | 0.543333 | 0.901× | 0.896× |
| `-s autoremove` | 0.810000 | 0.040000 | 0.850000 | 0.942× | 0.945× |
| `-s install rpm-build` | 1.283333 | 0.050000 | 1.333333 | 0.943× | 0.945× |
| `-s install openuds-server` | 3.896667 | 0.083333 | 3.980000 | 0.962× | 0.961× |
| `-s install password-store` | 1.310000 | 0.050000 | 1.360000 | 0.941× | 0.944× |
+14
View File
@@ -152,6 +152,20 @@ set-строка
Оставляя изначальную идею слитого декодера, была написана его реимлементация, использующая более простую логику, но использующая 64-битные блоки, а также упрощённую precompiled таблицу. (???) если есть результаты ускорения, сюда надо
### 4.6. Тесты производительности
Для проверки производительности сравнивались две локальные сборки `librpm`: исходная реализация и версия с описанными изменениями. Замеры выполнялись на одинаковых симуляционных командах `apt-get`.
Коэффициент считается как отношение времени исходной реализации к времени изменённой. Значение больше `1` - ускорение, меньше `1` - замедление.
| Команда | `set.c` user, с | `set.c` system, с | `set9.c` user, с | `set9.c` system, с | Ускорение по user | Ускорение по user+system |
| --------------------------- | --------------: | ----------------: | ---------------: | -----------------: | ----------------: | -----------------------: |
| `-s check` | 0.453 | 0.033 | 0.503 | 0.040 | 0.901× | 0.896× |
| `-s autoremove` | 0.763 | 0.040 | 0.810 | 0.040 | 0.942× | 0.945× |
| `-s install rpm-build` | 1.210 | 0.050 | 1.283 | 0.050 | 0.943× | 0.945× |
| `-s install openuds-server` | 3.747 | 0.080 | 3.897 | 0.083 | 0.962× | 0.961× |
| `-s install password-store` | 1.233 | 0.050 | 1.310 | 0.050 | 0.941× | 0.944× |
## 5. Прочие исследования
В данной главе собраны исследования, которые не вошли непосредственно в реализацию новой версии, однако важны своими идеями и результатами.
+119
View File
@@ -0,0 +1,119 @@
\Title{Гудов Д.О.}{Исследование алгоритма разрешения зависимостей в ALT RPM}
\section*{Введение}
Одной из задач пакетного менеджера является проверка совместимости устанавливаемого программного обеспечения с уже имеющимися или одновременно устанавливаемыми библиотеками. Традиционная зависимость от имени библиотеки и номера её версии не всегда достаточна: отдельный экспортируемый символ может быть удалён без изменения SONAME, а библиотеки с одинаковым SONAME могут предоставлять различные программные интерфейсы. В результате формально удовлетворённая зависимость от версии ещё не гарантирует, что динамический загрузчик найдёт все символы, необходимые программе.
В ALT RPM эта задача решается при помощи специальных версий зависимостей вида \texttt{set:<encoded-set>} [\Ref{SETC}]. Для отношения \texttt{Provides} такая строка описывает множество символов, экспортируемых библиотекой, а для отношения \texttt{Requires} --- символы, требуемые программой от конкретной библиотеки. При проверке зависимости обычное сравнение версий заменяется проверкой включения множеств. Полные имена символов при этом не сохраняются: они заменяются усечёнными хеш-значениями, сортируются и кодируются в компактную строку, допустимую как версия RPM.
Цель настоящей работы --- исследовать алгоритм построения и сравнения \texttt{set:}-строк, оценить вероятностные свойства хэша и вычислительную сложность алгоритма, а также определить направления оптимизации реализации.
%% В первых разделах формализуется решаемая задача, рассматриваются реальные данные репозитория Sisyphus, формат строки и путь её построения в исходной реализации \texttt{lib/set.c}.
\section{Постановка задачи и данные ALT Linux}
\label{PROBLEM}
Пусть $P$ --- множество символов, предоставляемых библиотекой, а $R$ --- множество символов, требуемых от неё программой. Обозначим $p=|P|$ и $r=|R|$. Зависимость выполнима тогда и только тогда, когда
\[
R\subseteq P.
\]
Списки символов формируются механизмом автоматического определения зависимостей \texttt{rpm-build}. Для \texttt{Provides} из динамической таблицы библиотеки выбираются доступные извне определённые символы. Для \texttt{Requires} утилита \texttt{ldd --bindings} устанавливает соответствие между требуемым символом и конкретной библиотекой-поставщиком; слабые неопределённые символы исключаются. Таким образом, одна строка \texttt{Requires} содержит только множество, связанное с данным поставщиком.
Явное хранение имён увеличивало бы RPM-метаданные пропорционально их суммарной длине. Поэтому используется усечённая хеш-функция c целым $b$, называемого в реализации \texttt{bpp},
\[
h_b(x)=h_{32}(x)\bmod 2^b,
\qquad
H_b(S)=\{h_b(x)\mid x\in S\},
\]
где $h_{32}$ --- 32-битная функция Jenkins one-at-a-time. Фактически \texttt{lib/set.c} проверяет условие
\[
H_b(R)\subseteq H_b(P).
\]
Такое представление сохраняет включение: из $R\subseteq P$ следует $H_b(R)\subseteq H_b(P)$. Следовательно, коллизия хешей не создаёт ложного отказа для корректной зависимости. Обратное утверждение неверно: отсутствующий символ из $R\setminus P$ может получить то же усечённое значение, что и один из символов $P$, и привести к ложному принятию зависимости. Тем самым предоставляемая гарантия имеет вероятностный характер.
Для оценки реальной нагрузки был исследован срез репозитория Sisyphus для архитектур \texttt{x86\_64} и \texttt{noarch}. Объём рассмотренных метаданных на момент 2026-08-20 приведён в табл.~\Ref{CORPUS}.
\begin{table}[H]
\begin{center}
\caption{\label{CORPUS}Объём исследованного среза Sisyphus}
\small
\begin{tabular}{|l|r|}
\hline
Объект & Количество \\
\hline
Пакеты & 47\,654 \\
\hline
Отношения \texttt{Provides} с \texttt{set:}-версией & 14\,859 \\
\hline
Отношения \texttt{Requires} с \texttt{set:}-версией & 69\,153 \\
\hline
Сопоставленные пары $P,R$ & 68\,492 \\
\hline
\end{tabular}
\end{center}
\end{table}
661 отношений удовлетворены обычным неверсионированным \texttt{Provides}.
Для каждой сопоставленной пары декодировались мощности множеств $p$ и $r$, а также вычислялось индивидуальное отношение $p/r$. Квантили этих величин показаны в табл.~\Ref{CARDINALITIES}. Квантили отношения вычислялись непосредственно по парам.
\begin{table}[H]
\begin{center}
\caption{\label{CARDINALITIES}Мощности множеств в парах \texttt{Provides}/\texttt{Requires}}
\small
\begin{tabular}{|c|r|r|r|}
\hline
Квантиль & $p$ & $r$ & $p/r$ \\
\hline
0,50 & 480 & 13 & 28,1 \\
\hline
0,75 & 1\,886 & 37 & 80 \\
\hline
0,90 & 6\,219 & 104 & 257 \\
\hline
\end{tabular}
\end{center}
\end{table}
В 92,4\% сопоставленных пар выполняется $p/r\geq 4$. Следовательно, типичный проверяемый набор требований существенно разрежен относительно множества предоставляемых символов. Это наблюдение важно для алгоритма сравнения: последовательный симметричный просмотр двух массивов не всегда использует характерное различие их мощностей.
\section{Устройство существующей \texttt{set:}-строки}
\label{FORMAT}
Построение \texttt{set:}-строки выполняется как последовательность преобразований
\[
\begin{aligned}
\text{имена символов}
&\longrightarrow \text{усечённые хеши}
\longrightarrow \text{сортировка},\\
&\longrightarrow \text{удаление повторов и вычисление дельт},\\
&\longrightarrow \text{код Голомба--Райса}
\longrightarrow \text{Base62-представление}.
\end{aligned}
\]
Итоговая версия имеет вид
\[
\texttt{set:}\langle b\rangle\langle m\rangle\langle payload\rangle.
\]
Префикс \texttt{set:} распознаётся RPM как признак специальной версии. Следующие два символа кодируют параметры $b=\texttt{bpp}$ и $m=\texttt{Mshift}$ по правилу $c=v-7+\texttt{'a'}$. Допустимы $10\leq b\leq32$, $7\leq m\leq31$ и $m<b$. Оставшаяся часть строки содержит закодированный в \texttt{Base62} битовый поток.
\subsection{Хеширование и вероятность коллизий}
Для каждого имени вычисляется 32-битный Jenkins one-at-a-time [\Ref{JENKINS}], после чего сохраняются только $b$ младших бит. Пусть $n$ различных имён независимо и равномерно отображаются в пространство из $N=2^b$ значений. Тогда математическое ожидание числа столкнувшихся пар равно
\References
\begin{enumerate}
\item
\Label{SETC}
Tourbin A.
\emph{set.c --- base62, Golomb and set-string routines}.
ALT RPM source code, 2010--2012.
[Электронный ресурс] URL: \url{https://git.altlinux.org/gears/r/rpm.git?a=blob;f=lib/set.c}.
\item
\Label{JENKINS}
\end{enumerate}
+141
View File
@@ -0,0 +1,141 @@
%% ---------------------------------------------------------------------------
\documentclass[openany, twoside, a4paper, 10pt]{extbook}
%% ---------------------------------------------------------------------------
\usepackage[utf8]{inputenc}
\usepackage[english, russian]{babel}
%% ---------------------------------------------------------------------------
\usepackage{indentfirst}
\frenchspacing
\raggedbottom
%% ---------------------------------------------------------------------------
\usepackage{url}
%% ---------------------------------------------------------------------------
\usepackage{ifpdf}
\ifpdf
\usepackage[pdftex]{graphicx}
\usepackage{cmap}
\pdfcompresslevel=9
\DeclareGraphicsExtensions{.pdf,.png,.jpg}
\else
\usepackage[dvips]{graphicx}
\DeclareGraphicsExtensions{.eps}
\fi
\graphicspath{ {./images/} }
%% ---------------------------------------------------------------------------
\usepackage{float}
\restylefloat{table}
\usepackage{multirow}
%% ---------------------------------------------------------------------------
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{amscd}
\usepackage{bm}
\usepackage{caption}
\usepackage{makecell}
\usepackage{nameref}
%% ---------------------------------------------------------------------------
\usepackage{titlesec}
\titleformat{\section}[block]{\rmfamily\Large\bfseries\filcenter}{\thesection.}{1em}{}
%% ---------------------------------------------------------------------------
\sloppy
%% ---------------------------------------------------------------------------
% a5paper: 148 x 210
% print area: 110 x 180
% top = bottom = (210 - 180) / 2 = 15
% left = right = (148 - 110) / 2 = 19
\usepackage[%
left=5cm,%
top=5.85cm,%
right=5cm,%
bottom=5.85cm,%
headsep=0.2cm,%
footskip=0.5cm,%
]{geometry}
%% ---------------------------------------------------------------------------
\usepackage{titlesec}
\newpagestyle{lvkpagestyle}{
\sethead{}{}{}
\setfoot{}{\usepage}{}
}
\pagestyle{lvkpagestyle}
%% ---------------------------------------------------------------------------
\makeatletter
\newcommand\Title[2]{%
%\par
\begin{centering}
\medskip
{
\textbf{#1} \\
}
{
\Large
\textbf{\textsc{#2}} \\
}
\bigskip
\end{centering}
\@afterheading
}
\makeatother
%% ---------------------------------------------------------------------------
\makeatletter
\newcommand{\References}{
\medskip
\section*{Литература}
\nopagebreak
\medskip
\@afterheading
}
\makeatother
\makeatletter
\newcommand{\ReferencesEng}{
\medskip
\section*{References}
\nopagebreak
\medskip
\@afterheading
}
\makeatother
%% ---------------------------------------------------------------------------
\makeatletter
\newcommand{\unchapter}[1]{%
\begingroup
\let\@makechapterhead\@gobble % make \@makechapterhead do nothing
\chapter{#1}
\endgroup
}
\makeatother
%% ---------------------------------------------------------------------------
\makeatletter
\newcommand{\startgroup}[1]{\addtocontents{toc}{\contentsline{chapter}{#1}{}}}
\makeatother
%% ---------------------------------------------------------------------------
\renewcommand*\thesection{\arabic{section}}
\newcommand{\AddRefPrefix}[1]{
\renewcommand{\Pageref}[1]{\pageref{#1##1}}
\renewcommand{\Ref}[1]{\ref{#1##1}}
\renewcommand{\Label}[1]{\label{#1##1}}
}
%%\newcommand{\Ref}[1]{\ref{#1}}
\newcommand{\Pageref}[1]{\pageref{#1}}
\newcommand{\Label}[1]{\label{#1}}
%% ---------------------------------------------------------------------------
\renewcommand{\thetable}{\arabic{table}}
\renewcommand{\thefigure}{\arabic{figure}}
%% ---------------------------------------------------------------------------
\usepackage{pdfpages}
%% ---------------------------------------------------------------------------
\begin{document}
%% \setcounter{page}{3}
\setcounter{tocdepth}{0}
%% \tableofcontents
%% ---------------------------------------------------------------------------
% \startgroup{Секция 1. Разные вещи}
% \unchapter{\textnormal{\textit{Иванов И.И.}} Первая статья в сборнике}
% \AddRefPrefix{th1}
\input{article_hbd}
%% ---------------------------------------------------------------------------
\end{document}
%% ---------------------------------------------------------------------------
+168 -135
View File
@@ -3,15 +3,19 @@ import argparse
import ctypes
import gc
import os
import shutil
import statistics
import subprocess
import time
import sys
import tempfile
from pathlib import Path
HERE = Path(__file__).resolve().parent
BUILD = HERE / "build"
LIBC = ctypes.CDLL(None)
LIBC.free.argtypes = [ctypes.c_void_p]
TIME_COMMAND = os.environ.get("TIME_COMMAND") or shutil.which("time") or "/usr/bin/time"
TIME_FORMAT = "%U\t%S"
class SetAPI:
@@ -49,108 +53,132 @@ class SetAPI:
return encoded
def median_fini(api, symbols, bpp, calls, rounds):
samples = []
for _ in range(rounds):
sets = [api.new_with_symbols(symbols) for _ in range(calls)]
results = []
start = time.perf_counter_ns()
for value in sets:
results.append(api.lib.set_fini(value, bpp))
samples.append((time.perf_counter_ns() - start) / calls)
if not all(results):
raise RuntimeError("set_fini returned NULL")
encoded = [ctypes.string_at(result) for result in results]
if len(set(encoded)) != 1:
raise RuntimeError("set_fini is not deterministic")
for value, result in zip(sets, results):
api.release(value, result)
return statistics.median(samples)
def make_symbols(args):
symbols = tuple(
f"symbol_{i:08d}_version_ALT_{i % 97}".encode() for i in range(args.symbols)
)
required = (
symbols[::2]
if args.required is None
else tuple(symbols[i * args.symbols // args.required] for i in range(args.required))
)
return symbols, required
def median_build(api, symbols, bpp, calls, rounds):
samples = []
for _ in range(rounds):
sets = []
results = []
start = time.perf_counter_ns()
for _ in range(calls):
def api_for(name):
if name == "set9":
return SetAPI(BUILD / "libset9.so")
if name == "direct":
return SetAPI(BUILD / "libdirect-hash.so")
raise ValueError(f"unknown implementation: {name}")
def child_main(args):
symbols, required = make_symbols(args)
api = api_for(args.time_child_impl)
checksum = 0
if args.time_child_operation == "fini":
# Measured by /usr/bin/time around this child process. The repeated work
# is set construction plus set_fini; keeping construction in the same
# child avoids Python-side subsection timers while still reporting CPU
# user/system time from the external time utility.
for _ in range(args.fini_calls):
value = api.new_with_symbols(symbols)
result = api.lib.set_fini(value, bpp)
sets.append(value)
results.append(result)
samples.append((time.perf_counter_ns() - start) / calls)
if not all(results):
result = api.lib.set_fini(value, args.bpp)
if not result:
raise RuntimeError("set_fini returned NULL")
for value, result in zip(sets, results):
checksum ^= len(ctypes.string_at(result))
api.release(value, result)
return statistics.median(samples)
def median_add(api, symbols, calls, rounds):
samples = []
for _ in range(rounds):
values = []
start = time.perf_counter_ns()
for _ in range(calls):
values.append(api.new_with_symbols(symbols))
samples.append((time.perf_counter_ns() - start) / calls)
for value in values:
elif args.time_child_operation == "add":
for _ in range(args.fini_calls):
value = api.new_with_symbols(symbols)
checksum ^= int(value)
api.lib.set_free(value)
return statistics.median(samples)
def median_cmp(api, provider, requirement, calls, rounds):
elif args.time_child_operation == "build":
for _ in range(args.fini_calls):
value = api.new_with_symbols(symbols)
result = api.lib.set_fini(value, args.bpp)
if not result:
raise RuntimeError("set_fini returned NULL")
checksum ^= len(ctypes.string_at(result))
api.release(value, result)
elif args.time_child_operation == "cmp-cold":
provider = api.encode(symbols, args.bpp)
requirement = api.encode(required, args.bpp)
for _ in range(args.cold_calls):
pid = os.fork()
if pid == 0:
result = api.lib.rpmsetcmp(provider, requirement)
os._exit(0 if result == 1 else 1)
_, status = os.waitpid(pid, 0)
if status != 0:
raise RuntimeError(f"cold rpmsetcmp child failed: status={status}")
checksum += 1
elif args.time_child_operation == "cmp-warm":
provider = api.encode(symbols, args.bpp)
requirement = api.encode(required, args.bpp)
expected = api.lib.rpmsetcmp(provider, requirement)
if expected != 1 or api.lib.rpmsetcmp(provider, provider) != 0:
raise RuntimeError(f"unexpected rpmsetcmp result: {expected}")
for _ in range(100):
api.lib.rpmsetcmp(provider, requirement)
samples = []
for _ in range(rounds):
checksum = 0
start = time.perf_counter_ns()
for _ in range(calls):
for _ in range(args.cmp_calls):
checksum += api.lib.rpmsetcmp(provider, requirement)
samples.append((time.perf_counter_ns() - start) / calls)
if checksum != calls:
if checksum != args.cmp_calls:
raise RuntimeError("rpmsetcmp result changed during benchmark")
return statistics.median(samples)
else:
raise RuntimeError(f"unknown timed operation: {args.time_child_operation}")
# Keep a small observable side effect so timed loops are not optimized away
# inside the C library or by future wrappers.
print(checksum, file=sys.stderr)
def cold_cmp_once(api, provider, requirement):
read_fd, write_fd = os.pipe()
pid = os.fork()
if pid == 0:
os.close(read_fd)
start = time.perf_counter_ns()
result = api.lib.rpmsetcmp(provider, requirement)
elapsed = time.perf_counter_ns() - start
os.write(write_fd, f"{elapsed} {result}".encode())
os.close(write_fd)
os._exit(0)
os.close(write_fd)
payload = b""
while chunk := os.read(read_fd, 128):
payload += chunk
os.close(read_fd)
_, status = os.waitpid(pid, 0)
if status != 0:
raise RuntimeError(f"cold rpmsetcmp child failed: status={status}")
elapsed, result = map(int, payload.split())
if result != 1:
raise RuntimeError(f"unexpected cold rpmsetcmp result: {result}")
return elapsed
def median_cmp_cold(api, provider, requirement, calls, rounds):
def measure_with_time(args, implementation, operation, calls):
samples = []
for _ in range(rounds):
total = sum(cold_cmp_once(api, provider, requirement) for _ in range(calls))
samples.append(total / calls)
return statistics.median(samples)
for _ in range(args.rounds):
with tempfile.NamedTemporaryFile(prefix="arsv-time-", delete=False) as handle:
time_path = Path(handle.name)
command = [
TIME_COMMAND,
"-f",
TIME_FORMAT,
"-o",
str(time_path),
"--",
sys.executable,
str(Path(__file__).resolve()),
"--skip-build",
"--time-child",
"--time-child-impl",
implementation,
"--time-child-operation",
operation,
"--symbols",
str(args.symbols),
"--bpp",
str(args.bpp),
"--rounds",
"1",
"--fini-calls",
str(args.fini_calls),
"--cmp-calls",
str(args.cmp_calls),
"--cold-calls",
str(args.cold_calls),
]
if args.required is not None:
command.extend(["--required", str(args.required)])
try:
subprocess.run(command, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
user_text, system_text = time_path.read_text().split()
finally:
time_path.unlink(missing_ok=True)
samples.append((float(user_text) / calls, float(system_text) / calls))
users = [sample[0] for sample in samples]
systems = [sample[1] for sample in samples]
return statistics.median(users), statistics.median(systems)
def verify_complete_decoding(api, provider, requirement):
@@ -167,11 +195,17 @@ def verify_complete_decoding(api, provider, requirement):
raise RuntimeError("second operand was not decoded and validated completely")
def format_time(ns):
return f"{ns / 1000:.2f} us"
def format_cpu_time(seconds):
return f"{seconds * 1_000_000:.2f} us"
def main():
def format_ratio(new, old):
if old == 0:
return "n/a"
return f"{new / old:.2f}x"
def build_parser():
parser = argparse.ArgumentParser(description="Compare set9 and direct-hash set APIs")
parser.add_argument("--symbols", type=int, default=1000)
parser.add_argument(
@@ -185,6 +219,18 @@ def main():
parser.add_argument("--cmp-calls", type=int, default=2000)
parser.add_argument("--cold-calls", type=int, default=20)
parser.add_argument("--skip-build", action="store_true")
parser.add_argument("--time-child", action="store_true", help=argparse.SUPPRESS)
parser.add_argument("--time-child-impl", choices=("set9", "direct"), help=argparse.SUPPRESS)
parser.add_argument(
"--time-child-operation",
choices=("fini", "add", "build", "cmp-cold", "cmp-warm"),
help=argparse.SUPPRESS,
)
return parser
def main():
parser = build_parser()
args = parser.parse_args()
if args.symbols < 2 or not 10 <= args.bpp <= 32:
parser.error("symbols must be >= 2 and bpp must be in 10..32")
@@ -192,26 +238,27 @@ def main():
parser.error("required must be in 1..symbols-1")
if min(args.rounds, args.fini_calls, args.cmp_calls, args.cold_calls) < 1:
parser.error("rounds and call counts must be positive")
if args.time_child and not (args.time_child_impl and args.time_child_operation):
parser.error("--time-child requires --time-child-impl and --time-child-operation")
if not args.skip_build:
subprocess.run([str(HERE / "build.sh")], check=True)
symbols = tuple(
f"symbol_{i:08d}_version_ALT_{i % 97}".encode() for i in range(args.symbols)
)
required = (
symbols[::2]
if args.required is None
else tuple(symbols[i * args.symbols // args.required] for i in range(args.required))
)
if args.time_child:
child_main(args)
return
if not Path(TIME_COMMAND).is_file():
raise RuntimeError(f"time executable not found: {TIME_COMMAND}")
symbols, required = make_symbols(args)
apis = {
"set9": SetAPI(BUILD / "libset9.so"),
"direct": SetAPI(BUILD / "libdirect-hash.so"),
"set9": api_for("set9"),
"direct": api_for("direct"),
}
gc.disable()
try:
timings = {name: [[] for _ in range(5)] for name in apis}
lengths = {}
encoded = {}
for name, api in apis.items():
@@ -221,31 +268,20 @@ def main():
wire_format = "D1/base64" if provider.startswith(b"D1") else "golomb/base62"
lengths[name] = (len(provider), wire_format)
operations = (
lambda name, api: median_fini(api, symbols, args.bpp, args.fini_calls, 1),
lambda name, api: median_add(api, symbols, args.fini_calls, 1),
lambda name, api: median_build(api, symbols, args.bpp, args.fini_calls, 1),
lambda name, api: median_cmp_cold(
api, encoded[name][0], encoded[name][1], args.cold_calls, 1
),
lambda name, api: median_cmp(
api, encoded[name][0], encoded[name][1], args.cmp_calls, 1
),
)
names = tuple(apis)
for operation_index, operation in enumerate(operations):
for round_index in range(args.rounds):
order = names if round_index % 2 == 0 else tuple(reversed(names))
for name in order:
timings[name][operation_index].append(operation(name, apis[name]))
timings = {
name: tuple(statistics.median(samples) for samples in operation_samples)
for name, operation_samples in timings.items()
}
# Run validation after timing: forked cold samples must inherit an empty
# decoded-set cache from the parent process.
for name, api in apis.items():
verify_complete_decoding(api, *encoded[name])
operations = (
("set_fini child", "fini", args.fini_calls),
("new+add child", "add", args.fini_calls),
("new+add+fini child", "build", args.fini_calls),
("rpmsetcmp cold", "cmp-cold", args.cold_calls),
("rpmsetcmp warm", "cmp-warm", args.cmp_calls),
)
timings = {name: [] for name in apis}
for label, operation, calls in operations:
for name in apis:
timings[name].append(measure_with_time(args, name, operation, calls))
finally:
gc.enable()
@@ -253,18 +289,15 @@ def main():
print("implementation set_chars format")
for name in apis:
print(f"{name:<14} {lengths[name][0]:>9} {lengths[name][1]}")
print("\noperation set9 direct direct/set9")
labels = (
"set_fini only",
"new+add (ctypes)",
"new+add+fini (ctypes)",
"rpmsetcmp cold",
"rpmsetcmp warm",
print("\noperation set9_user set9_sys direct_user direct_sys user_ratio sys_ratio")
for index, (label, _operation, _calls) in enumerate(operations):
old_user, old_sys = timings["set9"][index]
new_user, new_sys = timings["direct"][index]
print(
f"{label:<22} {format_cpu_time(old_user):>10} {format_cpu_time(old_sys):>9} "
f"{format_cpu_time(new_user):>11} {format_cpu_time(new_sys):>10} "
f"{format_ratio(new_user, old_user):>10} {format_ratio(new_sys, old_sys):>9}"
)
for index, label in enumerate(labels):
old = timings["set9"][index]
new = timings["direct"][index]
print(f"{label:<22} {format_time(old):>10} {format_time(new):>10} {new / old:>12.2f}x")
if __name__ == "__main__":
+25 -18
View File
@@ -16,6 +16,7 @@ PERF_EVENTS='task-clock,context-switches,cpu-migrations,page-faults,minor-faults
PACKAGER='krosh <gudovdo@my.msu.ru>'
APT_SOURCE=/etc/apt/sources.list.d/alt.list
APT_GET=/usr/lib/apt/apt-get
TIME_COMMAND=/usr/bin/time
RPM_BUILD_GIT=https://git.altlinux.org/gears/r/rpm-build.git
RPM_GIT=https://git.altlinux.org/gears/r/rpm.git
@@ -93,7 +94,7 @@ operation_label()
run_once()
{
local operation=$1 variant=$2 run=$3 start end status perf_stat
local operation=$1 variant=$2 run=$3 status perf_stat time_file
local libdir="$variant/lib/usr/lib64"
local root="$COMMON/root"
local raw="$variant/raw"
@@ -117,8 +118,9 @@ run_once()
)
fi
start=$(date +%s%N)
if env LC_ALL=C APT_CONFIG="$COMMON/apt.conf" \
time_file="$raw/$operation.$run.time.tsv"
if "$TIME_COMMAND" -f $'%U\t%S' -o "$time_file" -- \
env LC_ALL=C APT_CONFIG="$COMMON/apt.conf" \
LD_LIBRARY_PATH="$libdir" \
taskset -c "$CPU" "${command[@]}" \
>"$raw/$operation.$run.stdout" \
@@ -127,10 +129,7 @@ run_once()
else
status=$?
fi
end=$(date +%s%N)
RUN_TIME=$(awk -v start="$start" -v end="$end" \
'BEGIN { printf "%.6f", (end - start) / 1000000000 }')
read -r RUN_USER_TIME RUN_SYSTEM_TIME <"$time_file"
RUN_STATUS=$status
}
@@ -228,8 +227,8 @@ benchmark_variant()
{
local variant=$1 result=$2 debug_file=$3 debuginfo_rpm=$4
local runtime_file=$5 dso_name=$6
local operation run average label status_text perf_result perf_dir
local -a times statuses
local operation run average_user average_system label status_text perf_result perf_dir
local -a user_times system_times statuses
local -a operations=(
check
autoremove
@@ -241,7 +240,7 @@ benchmark_variant()
)
mkdir -p "$variant/raw/perf-stat"
printf 'command\taverage_seconds\trun1_seconds\trun2_seconds\trun3_seconds\texit_status\n' \
printf 'command\taverage_user_seconds\taverage_system_seconds\trun1_user_seconds\trun1_system_seconds\trun2_user_seconds\trun2_system_seconds\trun3_user_seconds\trun3_system_seconds\texit_status\n' \
>"$result"
perf_result=${result%.tsv}.perf-stat.tsv
perf_dir=${result%.tsv}.perf
@@ -257,22 +256,27 @@ benchmark_variant()
fi
for operation in "${operations[@]}"; do
times=()
user_times=()
system_times=()
statuses=()
for ((run = 1; run <= RUNS; ++run)); do
run_once "$operation" "$variant" "$run"
times+=("$RUN_TIME")
user_times+=("$RUN_USER_TIME")
system_times+=("$RUN_SYSTEM_TIME")
statuses+=("$RUN_STATUS")
if ((COLLECT_PERF)); then
append_perf_stat "$operation" "$run" \
"$variant/raw/perf-stat/$operation.$run.tsv" "$perf_result"
fi
printf '%s: run %d/%d: %ss, status=%s\n' \
"$operation" "$run" "$RUNS" "$RUN_TIME" "$RUN_STATUS"
printf '%s: run %d/%d: user=%ss system=%ss status=%s\n' \
"$operation" "$run" "$RUNS" \
"$RUN_USER_TIME" "$RUN_SYSTEM_TIME" "$RUN_STATUS"
done
average=$(printf '%s\n' "${times[@]}" | \
average_user=$(printf '%s\n' "${user_times[@]}" | \
awk '{ total += $1 } END { printf "%.6f", total / NR }')
average_system=$(printf '%s\n' "${system_times[@]}" | \
awk '{ total += $1 } END { printf "%.6f", total / NR }')
status_text=${statuses[0]}
@@ -284,9 +288,11 @@ benchmark_variant()
done
label=$(operation_label "$operation")
printf '%s\t%s\t%s\t%s\t%s\t%s\n' \
"$label" "$average" \
"${times[0]}" "${times[1]}" "${times[2]}" "$status_text" \
printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' \
"$label" "$average_user" "$average_system" \
"${user_times[0]}" "${system_times[0]}" \
"${user_times[1]}" "${system_times[1]}" \
"${user_times[2]}" "${system_times[2]}" "$status_text" \
>>"$result"
if ((COLLECT_PERF && PERF_RECORD)); then
@@ -300,6 +306,7 @@ for command in git gear-hsh hsh rpm rpmquery rpm2cpio cpio apt-get apt-cache \
taskset awk sed date sha256sum ldd readelf readlink eu-unstrip; do
command -v "$command" >/dev/null || fail "required command not found: $command"
done
[[ -x $TIME_COMMAND ]] || fail "time executable not found: $TIME_COMMAND"
if ((COLLECT_PERF)); then
command -v perf >/dev/null || \
fail "perf is not installed; install the ALT package: apt-get install perf"