Debian Codegraph @

benchmark.py

raw
1 import io
2 import os
3 import platform
4 import re
5 import sqlite3
6 from collections import OrderedDict
7 from datetime import datetime
8 from random import choice
9 from subprocess import check_output
10 from time import time
11
12 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
13 import django
14 django.setup()
15
16 import matplotlib.pyplot as plt
17 import pandas as pd
18 import psycopg2
19 from django.conf import settings
20 from django.contrib.auth.models import Group, User
21 from django.core.cache import caches
22 from django.db import connection, connections
23 from django.test.utils import CaptureQueriesContext, override_settings
24 from django.utils.encoding import force_text
25 from MySQLdb import _mysql
26
27 import cachalot
28 from cachalot.api import invalidate
29 from cachalot.tests.models import Test
30
31
32 RESULTS_PATH = f"benchmark/docs/{datetime.now().date()}/"
33 CONTEXTS = ("Control", "Cold cache", "Hot cache")
34 DIVIDER = "divider"
35
36 LINUX_DATA_PATH = "/var/lib/"
37 DISK_DATA_RE = re.compile(r'^MODEL="(.*)" MOUNTPOINT="(.*)"$')
38
39
40 def get_disk_model_for_path_linux(path):
41 out = force_text(check_output(["lsblk", "-Po", "MODEL,MOUNTPOINT"]))
42 mount_points = []
43 previous_model = None
44 for model, mount_point in [
45 DISK_DATA_RE.match(line).groups() for line in out.split("\n") if line
46 ]:
47 if model:
48 previous_model = model.strip()
49 if mount_point:
50 mount_points.append((previous_model, mount_point))
51 mount_points = sorted(mount_points, key=lambda t: -len(t[1]))
52 for model, mount_point in mount_points:
53 if path.startswith(mount_point):
54 return model
55
56
57 def write_conditions():
58 versions = OrderedDict()
59 distribution = platform.uname()
60
61 # Linux
62 if distribution.system == "Linux":
63 # CPU
64 with open("/proc/cpuinfo") as f:
65 versions["CPU"] = re.search(
66 r"^model name\s+: (.+)$", f.read(), flags=re.MULTILINE
67 ).group(1)
68 # RAM
69 with open("/proc/meminfo") as f:
70 versions["RAM"] = re.search(
71 r"^MemTotal:\s+(.+)$", f.read(), flags=re.MULTILINE
72 ).group(1)
73 # Disk Model
74 versions.update((("Disk", get_disk_model_for_path_linux(LINUX_DATA_PATH)),))
75 # OS
76 versions["Linux distribution"] = f"{distribution.system} {distribution.release}"
77 # Darwin
78 else:
79 # CPU
80 versions["CPU"] = os.popen("sysctl -n machdep.cpu.brand_string").read().rstrip("\n")
81 # RAM
82 versions["RAM"] = os.popen("sysctl -n hw.memsize").read().rstrip("\n")
83 # Disk Model
84 versions["DISK"] = os.popen(
85 "diskutil info /dev/disk0 | grep 'Device / Media Name'"
86 ).read().split(":")[1].rstrip("\n").lstrip(" ")
87 # OS
88 versions["OS"] = f"{distribution.system} {distribution.release}"
89
90 versions.update(
91 (
92 ("Python", platform.python_version()),
93 ("Django", django.__version__),
94 ("cachalot", cachalot.__version__),
95 ("sqlite", sqlite3.sqlite_version),
96 )
97 )
98 # PostgreSQL
99 try:
100 with connections["postgresql"].cursor() as cursor:
101 cursor.execute("SELECT version();")
102 versions["PostgreSQL"] = re.match(
103 r"^PostgreSQL\s+(\S+)\s", cursor.fetchone()[0]
104 ).group(1)
105 except django.db.utils.OperationalError:
106 raise django.db.utils.OperationalError(
107 "You need a PostgreSQL DB called \"cachalot\" first. "
108 "Login with \"psql -U postgres -h localhost\" and run: "
109 "CREATE DATABASE cachalot;"
110 )
111 # MySQL
112 try:
113 with connections["mysql"].cursor() as cursor:
114 cursor.execute("SELECT version();")
115 versions["MySQL"] = cursor.fetchone()[0].split("-")[0]
116 except django.db.utils.OperationalError:
117 raise django.db.utils.OperationalError(
118 "You need a MySQL DB called \"cachalot\" first. "
119 "Login with \"mysql -u root\" and run: CREATE DATABASE cachalot;"
120 )
121 # Redis
122 out = force_text(check_output(["redis-cli", "INFO", "server"])).replace("\r", "")
123 versions["Redis"] = re.search(
124 r"^redis_version:([\d\.]+)$", out, flags=re.MULTILINE
125 ).group(1)
126 # memcached
127 out = force_text(check_output(["memcached", "-h"]))
128 versions["memcached"] = re.match(
129 r"^memcached ([\d\.]+)$", out, flags=re.MULTILINE
130 ).group(1)
131
132 versions.update(
133 (
134 ("psycopg2", psycopg2.__version__.split()[0]),
135 ("mysqlclient", _mysql.__version__),
136 )
137 )
138
139 with io.open(os.path.join(RESULTS_PATH, "conditions.rst"), "w") as f:
140 f.write(
141 "In this benchmark, a small database is generated, "
142 "and each test is executed %s times "
143 "under the following conditions:\n\n" % Benchmark.n
144 )
145
146 def write_table_sep(char="="):
147 f.write((char * 20) + " " + (char * 50) + "\n")
148
149 write_table_sep()
150 for k, v in versions.items():
151 f.write(k.ljust(20) + " " + v + "\n")
152 write_table_sep()
153
154
155 class AssertNumQueries(CaptureQueriesContext):
156 def __init__(self, n, using=None):
157 self.n = n
158 self.using = using
159 super(AssertNumQueries, self).__init__(self.get_connection())
160
161 def get_connection(self):
162 if self.using is None:
163 return connection
164 return connections[self.using]
165
166 def __exit__(self, exc_type, exc_val, exc_tb):
167 super(AssertNumQueries, self).__exit__(exc_type, exc_val, exc_tb)
168 if len(self) != self.n:
169 print(
170 "The amount of queries should be %s, but %s were captured."
171 % (self.n, len(self))
172 )
173
174
175 class Benchmark(object):
176 n = 20
177
178 def __init__(self):
179 self.data = []
180
181 def bench_once(self, context, num_queries, invalidate_before=False):
182 for _ in range(self.n):
183 if invalidate_before:
184 invalidate(db_alias=self.db_alias)
185 with AssertNumQueries(num_queries, using=self.db_alias):
186 start = time()
187 self.query_function(self.db_alias)
188 end = time()
189 self.data.append(
190 {
191 "query": self.query_name,
192 "time": end - start,
193 "context": context,
194 "db": self.db_vendor,
195 "cache": self.cache_name,
196 }
197 )
198
199 def benchmark(self, query_str, to_list=True, num_queries=1):
200 # Clears the cache before a single benchmark to ensure the same
201 # conditions across single benchmarks.
202 caches[settings.CACHALOT_CACHE].clear()
203
204 self.query_name = query_str
205 query_str = "Test.objects.using(using)" + query_str
206 if to_list:
207 query_str = "list(%s)" % query_str
208 self.query_function = eval("lambda using: " + query_str)
209
210 with override_settings(CACHALOT_ENABLED=False):
211 self.bench_once(CONTEXTS[0], num_queries)
212
213 self.bench_once(CONTEXTS[1], num_queries, invalidate_before=True)
214
215 self.bench_once(CONTEXTS[2], 0)
216
217 def execute_benchmark(self):
218 self.benchmark(".count()", to_list=False)
219 self.benchmark(".first()", to_list=False)
220 self.benchmark("[:10]")
221 self.benchmark("[5000:5010]")
222 self.benchmark(".filter(name__icontains='e')[0:10]")
223 self.benchmark(".filter(name__icontains='e')[5000:5010]")
224 self.benchmark(".order_by('owner')[0:10]")
225 self.benchmark(".order_by('owner')[5000:5010]")
226 self.benchmark(".select_related('owner')[0:10]")
227 self.benchmark(".select_related('owner')[5000:5010]")
228 self.benchmark(".prefetch_related('owner__groups')[0:10]", num_queries=3)
229 self.benchmark(".prefetch_related('owner__groups')[5000:5010]", num_queries=3)
230
231 def run(self):
232 for db_alias in settings.DATABASES:
233 self.db_alias = db_alias
234 self.db_vendor = connections[self.db_alias].vendor
235 print("Benchmarking %s…" % self.db_vendor)
236 for cache_alias in settings.CACHES:
237 cache = caches[cache_alias]
238 self.cache_name = cache.__class__.__name__[:-5].lower()
239 with override_settings(CACHALOT_CACHE=cache_alias):
240 self.execute_benchmark()
241
242 self.df = pd.DataFrame.from_records(self.data)
243 if not os.path.exists(RESULTS_PATH):
244 os.mkdir(RESULTS_PATH)
245 self.df.to_csv(os.path.join(RESULTS_PATH, "data.csv"))
246
247 self.xlim = (0, self.df["time"].max() * 1.01)
248 self.output("db")
249 self.output("cache")
250
251 def output(self, param):
252 gp = self.df.groupby(["context", "query", param])["time"]
253 self.means = gp.mean().unstack().unstack().reindex(CONTEXTS)
254 los = self.means - gp.min().unstack().unstack().reindex(CONTEXTS)
255 ups = gp.max().unstack().unstack().reindex(CONTEXTS) - self.means
256 self.errors = dict(
257 (
258 key,
259 dict(
260 (
261 subkey,
262 [
263 [los[key][subkey][context] for context in self.means.index],
264 [ups[key][subkey][context] for context in self.means.index],
265 ],
266 )
267 for subkey in self.means.columns.levels[1]
268 ),
269 )
270 for key in self.means.columns.levels[0]
271 )
272 self.get_perfs(param)
273 self.plot_detail(param)
274
275 gp = self.df.groupby(["context", param])["time"]
276 self.means = gp.mean().unstack().reindex(CONTEXTS)
277 los = self.means - gp.min().unstack().reindex(CONTEXTS)
278 ups = gp.max().unstack().reindex(CONTEXTS) - self.means
279 self.errors = [
280 [
281 [los[key][context] for context in self.means.index],
282 [ups[key][context] for context in self.means.index],
283 ]
284 for key in self.means
285 ]
286 self.plot_general(param)
287
288 def get_perfs(self, param):
289 with io.open(os.path.join(RESULTS_PATH, param + "_results.rst"), "w") as f:
290 for v in self.means.columns.levels[0]:
291 g = self.means[v].mean(axis=1)
292 perf = "%s is %.1f× slower then %.1f× faster" % (
293 v.ljust(10),
294 g[CONTEXTS[1]] / g[CONTEXTS[0]],
295 g[CONTEXTS[0]] / g[CONTEXTS[2]],
296 )
297 print(perf)
298 f.write("- %s\n" % perf)
299
300 def plot_detail(self, param):
301 for v in self.means.columns.levels[0]:
302 plt.figure()
303 axes = self.means[v].plot(
304 kind="barh",
305 xerr=self.errors[v],
306 xlim=self.xlim,
307 figsize=(15, 15),
308 subplots=True,
309 layout=(6, 2),
310 sharey=True,
311 legend=False,
312 )
313 plt.gca().invert_yaxis()
314 for row in axes:
315 for ax in row:
316 ax.xaxis.grid(True)
317 ax.set_ylabel("")
318 ax.set_xlabel("Time (s)")
319 plt.savefig(os.path.join(RESULTS_PATH, "%s_%s.svg" % (param, v)))
320
321 def plot_general(self, param):
322 plt.figure()
323 ax = self.means.plot(kind="barh", xerr=self.errors, xlim=self.xlim)
324 ax.invert_yaxis()
325 ax.xaxis.grid(True)
326 ax.set_ylabel("")
327 ax.set_xlabel("Time (s)")
328 plt.savefig(os.path.join(RESULTS_PATH, "%s.svg" % param))
329
330
331 def create_data(using):
332 User.objects.using(using).bulk_create(
333 [User(username="user%d" % i) for i in range(50)]
334 )
335 Group.objects.using(using).bulk_create(
336 [Group(name="test%d" % i) for i in range(10)]
337 )
338 groups = list(Group.objects.using(using))
339 for u in User.objects.using(using):
340 u.groups.add(choice(groups), choice(groups))
341 users = list(User.objects.using(using))
342 Test.objects.using(using).bulk_create(
343 [Test(name="test%d" % i, owner=choice(users)) for i in range(10000)]
344 )
345
346
347 if __name__ == "__main__":
348 if not os.path.exists(RESULTS_PATH):
349 os.mkdir(RESULTS_PATH)
350
351 write_conditions()
352
353 old_db_names = {}
354 for alias in connections:
355 conn = connections[alias]
356 old_db_names[alias] = conn.settings_dict["NAME"]
357 conn.creation.create_test_db(autoclobber=True)
358
359 print("Populating %s…" % connections[alias].vendor)
360 create_data(alias)
361
362 Benchmark().run()
363
364 for alias in connections:
365 connections[alias].creation.destroy_test_db(old_db_names[alias])