-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbenchmarks.py
executable file
·159 lines (135 loc) · 5.16 KB
/
benchmarks.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
#!/usr/bin/env python3
import datetime
import subprocess
import sys
import re
import serial
import numpy as np
from config import Settings
import os.path
def toLog(name, value, k=None):
if value > 20000:
value = f"{round(value/1000)}k"
else:
value = f"{value}"
return f"{name}: {value}\n"
def toMacro(name, value, k=None):
if value > 20000:
value = f"{round(value/1000):,}k"
else:
value = f"{value:,}"
value = value.replace(",", "\\,")
return f"\\def\\{name}{{{value}}}\n"
def run_bench(scheme_path, scheme_name, scheme_type, iterations):
subprocess.check_call(f"make clean", shell=True)
subprocess.check_call(f"make -j 12 IMPLEMENTATION_PATH={scheme_path} CRYPTO_ITERATIONS={iterations} bin/{scheme_name}_speed.bin", shell=True)
binary = f"bin/{scheme_name}_speed.bin"
if os.path.isfile(binary) is False:
print("Binary does not exist")
exit()
try:
subprocess.check_call(
f"st-flash --reset write {binary} 0x8000000", shell=True)
except:
print("st-flash failed --> retry")
subprocess.check_call(
f"st-flash erase && st-flash reset", shell=True)
return run_bench(scheme_path, scheme_name, scheme_type, iterations)
# get serial output and wait for '#'
with serial.Serial(Settings.SERIAL_DEVICE, 115200, timeout=10) as dev:
logs = []
iteration = 0
log = b""
while iteration < iterations:
device_output = dev.read()
if device_output == b'':
print("timeout --> retry")
return run_bench(scheme_path, scheme_name, scheme_type, iterations)
sys.stdout.buffer.write(device_output)
sys.stdout.flush()
log += device_output
if device_output == b'#':
logs.append(log)
log = b""
iteration += 1
return logs
def parseLogSpeed(log, ignoreErrors):
log = log.decode(errors="ignore")
if "error" in log.lower() and not ignoreErrors:
raise Exception("error in scheme. this is very bad.")
lines = str(log).splitlines()
def get(lines, key):
if key in lines:
return int(lines[1+lines.index(key)])
else:
return None
def cleanNullTerms(d):
return {
k:v
for k, v in d.items()
if v is not None
}
return cleanNullTerms({
f"keygen": get(lines, "keypair cycles:"),
f"encaps": get(lines, "encaps cycles:"),
f"decaps": get(lines, "decaps cycles:"),
f"sign": get(lines, "sign cycles:"),
f"verify": get(lines, "verify cycles:")
})
def average(results):
avgs = dict()
for key in results[0].keys():
avgs[key] = int(np.array([results[i][key] for i in range(len(results))]).mean())
return avgs
def bench(scheme_path, scheme_name, scheme_type, iterations, outfile, ignoreErrors=False):
logs = run_bench(scheme_path, scheme_name, scheme_type, iterations)
results = []
for log in logs:
try:
result = parseLogSpeed(log, ignoreErrors)
except:
breakpoint()
print("parsing log failed -> retry")
return bench(scheme_path, scheme_name, scheme_type, iterations, outfile)
results.append(result)
avgResults = average(results)
print(f"%M4 results for {scheme_name} (type={scheme_type})", file=outfile)
scheme_nameStripped = scheme_name.replace("-", "")
for key, value in avgResults.items():
macro = toMacro(f"{scheme_nameStripped}{key}", value)
print(macro.strip())
print(macro, end='', file=outfile)
print('', file=outfile, flush=True)
with open(f"benchmarks.txt", "a") as outfile:
now = datetime.datetime.now(datetime.timezone.utc)
iterations = 1000 # defines the number of measurements to perform
print(f"% Benchmarking measurements written on {now}; iterations={iterations}\n", file=outfile)
subprocess.check_call(f"make clean", shell=True)
# uncomment the scheme variants that should be build and evaluated
for scheme_path in [
# "crypto_kem/kyber512/old",
# "crypto_kem/kyber512/m4fstack",
# "crypto_kem/kyber512/m4fspeed",
# "crypto_kem/kyber512-90s/m4fstack",
# "crypto_kem/kyber512-90s/m4fspeed",
# "crypto_kem/kyber768/old",
# "crypto_kem/kyber768/m4fstack",
# "crypto_kem/kyber768/m4fspeed",
# "crypto_kem/kyber768-90s/m4fstack",
# "crypto_kem/kyber768-90s/m4fspeed",
# "crypto_kem/kyber1024/old",
# "crypto_kem/kyber1024/m4fstack",
# "crypto_kem/kyber1024/m4fspeed",
# "crypto_kem/kyber1024-90s/m4fstack",
# "crypto_kem/kyber1024-90s/m4fspeed",
# "crypto_kem/nttru",
"crypto_sign/dilithium2/old",
# "crypto_sign/dilithium2/new",
"crypto_sign/dilithium3/old",
# "crypto_sign/dilithium3/new",
"crypto_sign/dilithium5/old",
# "crypto_sign/dilithium5/new"
]:
scheme_name = scheme_path.replace("/", "_")
scheme_type = re.search('crypto_(.*?)_', scheme_name).group(1)
bench(scheme_path, scheme_name, scheme_type, iterations, outfile)