#!/usr/bin/env python3 """Run on the NEO4: python3 calibrate_neo4.py > neo4-calibration.json Read-only /proc and cpufreq sampling; a brief single-core arithmetic benchmark. No network, root, governor changes, file writes or user code execution. GPIO/SPI costs remain assumptions and need separate hardware measurement. """ import gc import json import os from pathlib import Path import statistics import sys import time def number_file(path, fallback): try: return float(Path(path).read_text().strip()) except (OSError, ValueError): return fallback def cpu_ticks(): values = [int(v) for v in Path('/proc/stat').read_text().splitlines()[0].split()[1:]] return sum(values[:8]), values[3] + values[4] def memory_info(): result = {} for line in Path('/proc/meminfo').read_text().splitlines(): key, value = line.split(':', 1) result[key] = int(value.strip().split()[0]) / 1024 return result def calibrate(): model_path = Path('/proc/device-tree/model') model = model_path.read_text().replace('\x00', '').strip() if 'NEO4' not in model.upper().replace(' ', ''): raise ValueError('Run this calibration on your NanoPi NEO4.') original_affinity = os.sched_getaffinity(0) if 4 not in original_affinity: raise ValueError('CPU4 (Cortex-A72) must be available for calibration.') os.sched_setaffinity(0, {4}) try: first = cpu_ticks() time.sleep(.3) second = cpu_ticks() background = 100 * (1 - (second[1]-first[1])/max(1, second[0]-first[0])) # Two executed Python lines per iteration. No tracing/profiling overhead. def benchmark(count): accumulator = 0 for n in range(count): accumulator = (accumulator + n) & 65535 return accumulator benchmark(100000) timings, frequencies = [], [] count = 750000 for _ in range(5): hz = number_file('/sys/devices/system/cpu/cpu4/cpufreq/scaling_cur_freq', 1800000) begin = time.process_time() benchmark(count) elapsed = time.process_time() - begin hz_after = number_file('/sys/devices/system/cpu/cpu4/cpufreq/scaling_cur_freq', hz) ghz = (hz + hz_after) / 2e6 frequencies.append(ghz) # Normalize the measured line cost to the model's 2GHz reference. timings.append(elapsed * 1e6 / (2*count) * ghz/2) gc.collect() memory = memory_info() private = 16. try: fields = {} for line in Path('/proc/self/smaps_rollup').read_text().splitlines(): if ':' in line: key, value = line.split(':', 1) fields[key] = float(value.strip().split()[0]) / 1024 private = fields.get('Private_Clean', 0) + fields.get('Private_Dirty', 0) except (OSError, ValueError): pass return {'schema':'neo4-calibration-v1', 'board':'NanoPi NEO4', 'parameters':{ 'reserved_mib':round(max(0,min(512,1024-memory['MemTotal'])),2), 'os_mib':round(max(16,min(950,memory['MemTotal']-memory['MemAvailable']-private)),2), 'os_cpu_percent':round(max(0,min(50,background)),2), 'python_private_mib':round(max(1,min(128,private)),2), 'line_us':round(max(.005,min(100,statistics.median(timings))),5), 'a72_ghz':round(max(.4,min(2,statistics.median(frequencies))),2)}, 'notes':['Partial calibration: OS baseline and a representative Python loop.', 'GPIO/SPI, shared libraries, native image costs and thermal jitter remain estimates.', 'MemAvailable subtracts reclaimable page cache; baseline depends on running services.']} finally: os.sched_setaffinity(0, original_affinity) if __name__ == '__main__': try: print(json.dumps(calibrate(), indent=2)) except (OSError, ValueError, AttributeError) as error: print(str(error), file=sys.stderr) raise SystemExit(1)