core,test: mem-bench харнес замера памяти (MemoryBench + membench.sh + mise task)
This commit is contained in:
@@ -0,0 +1,275 @@
|
||||
package ru.pjandro.wordpdf;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.lang.management.MemoryPoolMXBean;
|
||||
import java.lang.management.MemoryType;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import java.util.stream.Stream;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
/**
|
||||
* Замер памяти конвейера (НЕ тест: имя не матчается surefire-includes; запускается
|
||||
* {@code ./mise.sh run mem-bench} — см. {@code membench.sh} и
|
||||
* {@code docs/MEM_USAGE_UPGRADE.md}).
|
||||
*
|
||||
* <p>Для каждой конвертации печатает строку TSV {@code label scenario name iteration
|
||||
* peakBytes usedAfterBytes}: peakBytes — сумма пиков used всех heap-пулов
|
||||
* ({@link MemoryPoolMXBean}, пики сбрасываются перед конвертацией), usedAfterBytes —
|
||||
* used кучи сразу после конвертации без принудительного GC (тренд накопления;
|
||||
* {@code System.gc()} намеренно не вызывается). Суммарные аллокации и RSS не здесь:
|
||||
* JFR-{@code jdk.ObjectAllocationSample} пишет скрипт, VmHWM/VmRSS читаются из
|
||||
* {@code /proc/self/status} в конце сценария.</p>
|
||||
*
|
||||
* <p>Артефакт замера «до/после»: сравнение делает человек по выводам прогонов
|
||||
* с разными {@code MB_LABEL}; порогов внутри харнеса нет.</p>
|
||||
*/
|
||||
final class MemoryBench {
|
||||
|
||||
/** Лимиты входа завышены: валидатор не должен отсекать big-сценарий. */
|
||||
private static final ConvertOptions OPTIONS =
|
||||
new ConvertOptions(false, false, false, 1024L, 1_000_000);
|
||||
|
||||
/** Минимально допустимое значение циклов/повторов из аргументов. */
|
||||
private static final int MIN_POSITIVE = 1;
|
||||
/** Повторов body в синтетическом big-docx (детерминированный размер входа). */
|
||||
private static final int BODY_REPEATS = 400;
|
||||
|
||||
private MemoryBench() {
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
String label = env("MB_LABEL", "run");
|
||||
int loops = 10;
|
||||
int bigLoops = 5;
|
||||
String scenario = "all";
|
||||
String dir = null;
|
||||
int i = 0;
|
||||
while (i < args.length) {
|
||||
String a = args[i];
|
||||
if ("--loops".equals(a)) {
|
||||
loops = parsePositive(args, i);
|
||||
i += 2;
|
||||
} else if ("--big-loops".equals(a)) {
|
||||
bigLoops = parsePositive(args, i);
|
||||
i += 2;
|
||||
} else if ("--scenario".equals(a)) {
|
||||
scenario = args[i + 1];
|
||||
i += 2;
|
||||
} else if ("--dir".equals(a)) {
|
||||
dir = args[i + 1];
|
||||
i += 2;
|
||||
} else {
|
||||
System.out.printf(Locale.ROOT, "# unknown arg: %s%n", a);
|
||||
System.exit(2);
|
||||
}
|
||||
}
|
||||
|
||||
System.out.printf(Locale.ROOT, "# java.version %s%n",
|
||||
System.getProperty("java.version"));
|
||||
|
||||
if ("suite".equals(scenario) || "all".equals(scenario)) {
|
||||
runConversions(label, "suite", fixtures(), loops);
|
||||
}
|
||||
if ("big".equals(scenario) || "all".equals(scenario)) {
|
||||
byte[] base = readResource("samples/ru-plain.docx");
|
||||
byte[] big = bigDocx(base);
|
||||
System.out.printf(Locale.ROOT, "# big size %d%n", big.length);
|
||||
Map<String, byte[]> docs = new TreeMap<>();
|
||||
docs.put("big", big);
|
||||
runConversions(label, "big", docs, bigLoops);
|
||||
}
|
||||
if (dir != null) {
|
||||
runConversions(label, "dir", dirDocs(Paths.get(dir)), loops);
|
||||
}
|
||||
}
|
||||
|
||||
/** Прогон {@code loops} проходов по всем документам, TSV-строка на конвертацию. */
|
||||
private static void runConversions(String label, String scenario,
|
||||
Map<String, byte[]> docs, int loops) {
|
||||
long checksum = 0;
|
||||
for (int loop = 0; loop < loops; loop++) {
|
||||
for (Map.Entry<String, byte[]> doc : docs.entrySet()) {
|
||||
resetPeaks();
|
||||
try {
|
||||
byte[] pdf = WordPdfConverter.convert(doc.getValue(), "membench", OPTIONS);
|
||||
checksum += pdf.length;
|
||||
} catch (ConversionException e) {
|
||||
// отказ конвертации не обрывает замер — строка-комментарий в вывод
|
||||
System.out.printf(Locale.ROOT, "# error %s %s: %s%n",
|
||||
scenario, doc.getKey(), e.getMessage());
|
||||
}
|
||||
System.out.printf(Locale.ROOT, "%s\t%s\t%s\t%d\t%d\t%d%n",
|
||||
label, scenario, doc.getKey(), loop, sumPeakBytes(), heapUsedBytes());
|
||||
}
|
||||
}
|
||||
System.out.printf(Locale.ROOT, "# %s checksum-total %d%n", scenario, checksum);
|
||||
printProcMem();
|
||||
}
|
||||
|
||||
/** Фикстуры из classpath {@code ru/pjandro/wordpdf/samples} (25 файлов), по имени. */
|
||||
private static TreeMap<String, byte[]> fixtures() throws IOException, URISyntaxException {
|
||||
URL dir = MemoryBench.class.getClassLoader().getResource("samples");
|
||||
if (dir == null) {
|
||||
throw new IllegalStateException("samples/ не найден в classpath");
|
||||
}
|
||||
TreeMap<String, byte[]> out = new TreeMap<>();
|
||||
try (Stream<Path> files = Files.list(Paths.get(dir.toURI()))) {
|
||||
for (Path p : (Iterable<Path>) files.filter(MemoryBench::isDoc)::iterator) {
|
||||
out.put(p.getFileName().toString(), Files.readAllBytes(p));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Все {@code *.doc}/{@code *.docx} каталога PATH (реальные документы из develop/). */
|
||||
private static TreeMap<String, byte[]> dirDocs(Path dir) throws IOException {
|
||||
TreeMap<String, byte[]> out = new TreeMap<>();
|
||||
if (!Files.isDirectory(dir)) {
|
||||
System.out.printf(Locale.ROOT, "# dir %s отсутствует — пропущен%n", dir);
|
||||
return out;
|
||||
}
|
||||
try (Stream<Path> files = Files.list(dir)) {
|
||||
for (Path p : (Iterable<Path>) files.filter(MemoryBench::isDoc)::iterator) {
|
||||
out.put(p.getFileName().toString(), Files.readAllBytes(p));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static boolean isDoc(Path p) {
|
||||
String n = p.getFileName().toString().toLowerCase(Locale.ROOT);
|
||||
return n.endsWith(".doc") || n.endsWith(".docx");
|
||||
}
|
||||
|
||||
/**
|
||||
* Синтетический большой docx: body фикстуры ru-plain.docx (между {@code <w:body>}
|
||||
* и финальным {@code <w:sectPr>}) повторён {@link #BODY_REPEATS} раз, zip пересобран
|
||||
* DEFLATED в том же порядке записей. Детерминированно: тот же вход — тот же размер.
|
||||
*/
|
||||
private static byte[] bigDocx(byte[] base) throws IOException {
|
||||
Map<String, byte[]> entries = unzip(base);
|
||||
String xml = new String(entries.get("word/document.xml"), StandardCharsets.UTF_8);
|
||||
int bodyStart = xml.indexOf("<w:body>");
|
||||
int sectIdx = xml.lastIndexOf("<w:sectPr");
|
||||
if (sectIdx <= bodyStart) {
|
||||
// фикстура без секции (ru-plain.docx генератором) — якорь на закрытие body
|
||||
sectIdx = xml.lastIndexOf("</w:body>");
|
||||
}
|
||||
if (bodyStart < 0 || sectIdx <= bodyStart) {
|
||||
throw new IllegalStateException("в фикстуре не найден <w:body>...<w:sectPr>");
|
||||
}
|
||||
String inner = xml.substring(bodyStart + "<w:body>".length(), sectIdx);
|
||||
String grown = xml.substring(0, bodyStart + "<w:body>".length())
|
||||
+ inner.repeat(BODY_REPEATS)
|
||||
+ xml.substring(sectIdx);
|
||||
entries.put("word/document.xml", grown.getBytes(StandardCharsets.UTF_8));
|
||||
return rezip(entries);
|
||||
}
|
||||
|
||||
private static Map<String, byte[]> unzip(byte[] zip) throws IOException {
|
||||
Map<String, byte[]> entries = new LinkedHashMap<>();
|
||||
try (ZipInputStream zin = new ZipInputStream(new ByteArrayInputStream(zip))) {
|
||||
ZipEntry e;
|
||||
while ((e = zin.getNextEntry()) != null) {
|
||||
ByteArrayOutputStream part = new ByteArrayOutputStream();
|
||||
zin.transferTo(part);
|
||||
entries.put(e.getName(), part.toByteArray());
|
||||
}
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
private static byte[] rezip(Map<String, byte[]> entries) throws IOException {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
try (ZipOutputStream zos = new ZipOutputStream(out)) {
|
||||
for (Map.Entry<String, byte[]> e : entries.entrySet()) {
|
||||
zos.putNextEntry(new ZipEntry(e.getKey()));
|
||||
zos.write(e.getValue());
|
||||
zos.closeEntry();
|
||||
}
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private static byte[] readResource(String name) throws IOException {
|
||||
try (InputStream in = MemoryBench.class.getClassLoader().getResourceAsStream(name)) {
|
||||
if (in == null) {
|
||||
throw new IllegalStateException("ресурс не найден: " + name);
|
||||
}
|
||||
return in.readAllBytes();
|
||||
}
|
||||
}
|
||||
|
||||
private static void resetPeaks() {
|
||||
for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
|
||||
if (pool.getType() == MemoryType.HEAP) {
|
||||
try {
|
||||
pool.resetPeakUsage();
|
||||
} catch (UnsupportedOperationException e) {
|
||||
// пул без поддержки пиков (например «Tenured» в некоторых GC) — пропускаем
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static long sumPeakBytes() {
|
||||
long sum = 0;
|
||||
for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
|
||||
if (pool.getType() == MemoryType.HEAP) {
|
||||
try {
|
||||
sum += pool.getPeakUsage().getUsed();
|
||||
} catch (UnsupportedOperationException e) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
private static long heapUsedBytes() {
|
||||
return ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed();
|
||||
}
|
||||
|
||||
/** Память ОС: высокий water mark RSS процесса; на не-Linux — n/a. */
|
||||
private static void printProcMem() {
|
||||
try {
|
||||
for (String line : Files.readAllLines(Paths.get("/proc/self/status"))) {
|
||||
if (line.startsWith("VmHWM:") || line.startsWith("VmRSS:")) {
|
||||
System.out.printf(Locale.ROOT, "# %s%n", line.trim());
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
System.out.printf(Locale.ROOT, "# VmHWM n/a%n");
|
||||
}
|
||||
}
|
||||
|
||||
private static int parsePositive(String[] args, int i) {
|
||||
int value = Integer.parseInt(args[i + 1]);
|
||||
if (value < MIN_POSITIVE) {
|
||||
System.out.printf(Locale.ROOT, "# %s должен быть >= %d%n", args[i], MIN_POSITIVE);
|
||||
System.exit(2);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private static String env(String name, String def) {
|
||||
String value = System.getenv(name);
|
||||
return value == null || value.isEmpty() ? def : value;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user