Debian Codegraph @

benchmarks/run_benchmarks.py

raw
1 #!/usr/bin/env python
2 # ruff: noqa: E402
3 """
4 This benchmark package should be treated as work-in-progress, not a production
5 ready benchmarking solution for django-guardian.
6 """
7
8 import datetime
9 import os
10 import random
11 import string
12 import sys
13
14
15 def abspath(*args):
16 """Join path arguments and return their absolute path"""
17 return os.path.abspath(os.path.join(*args))
18
19
20 THIS_DIR = abspath(os.path.dirname(__file__))
21 ROOT_DIR = abspath(THIS_DIR, "..")
22
23 # so the preferred guardian module is one within this repo and
24 # not system-wide
25 sys.path.insert(0, ROOT_DIR)
26
27 os.environ["DJANGO_SETTINGS_MODULE"] = "benchmarks.settings"
28
29 import django
30
31 django.setup()
32
33 from django.contrib.auth.models import Group, User
34 from django.contrib.contenttypes.models import ContentType
35 from django.utils.termcolors import colorize
36
37 from benchmarks import settings
38 from benchmarks.models import TestDirectModel, TestModel
39 from benchmarks.utils import show_settings
40 from guardian.models import UserObjectPermission
41 from guardian.shortcuts import assign_perm
42
43 USERS_COUNT = 50
44 OBJECTS_COUNT = 100
45 OBJECTS_WIHT_PERMS_COUNT = 100
46
47
48 def random_string(length=25, chars=string.ascii_letters + string.digits):
49 return "".join(random.choice(chars) for i in range(length))
50
51
52 class Call:
53 def __init__(self, args, kwargs, start=None, finish=None):
54 self.args = args
55 self.kwargs = kwargs
56 self.start = start
57 self.finish = finish
58
59 def delta(self):
60 return self.finish - self.start
61
62
63 class Timed:
64 def __init__(self, action=None):
65 self.action = action
66
67 def __call__(self, func):
68 if not hasattr(func, "calls"):
69 func.calls = []
70
71 def wrapper(*args, **kwargs):
72 if self.action:
73 print(" -> [%s]" % self.action)
74 start = datetime.datetime.now()
75 call = Call(list(args), dict(kwargs), start)
76 try:
77 return func(*args, **kwargs)
78 finally:
79 call.finish = datetime.datetime.now()
80 func.calls.append(call)
81 if self.action:
82 print(f" -> [{self.action}] Done (Total time: {call.delta()})")
83
84 return wrapper
85
86
87 class Benchmark:
88 def __init__(self, name, users_count, objects_count, objects_with_perms_count, model, subquery):
89 self.name = name
90 self.users_count = users_count
91 self.objects_count = objects_count
92 self.objects_with_perms_count = objects_with_perms_count
93 self.subquery = subquery
94 self.Model = model
95 self.perm = "add_%s" % model._meta.model_name
96
97 def info(self, msg):
98 print(colorize(msg + "\n", fg="green"))
99
100 def prepare_db(self):
101 from django.core.management import call_command
102
103 call_command("makemigrations", interactive=False)
104 call_command("migrate", interactive=False)
105
106 for model in [User, Group, self.Model]:
107 model.objects.all().delete()
108
109 @Timed("Creating users")
110 def create_users(self):
111 User.objects.bulk_create(User(id=x, username=random_string().capitalize()) for x in range(self.users_count))
112
113 @Timed("Creating objects")
114 def create_objects(self):
115 Model = self.Model
116 Model.objects.bulk_create(Model(id=x, name=random_string(20)) for x in range(self.objects_count))
117
118 @Timed("Grant permissions")
119 def grant_perms(self):
120 ids = range(1, self.objects_count)
121 for user in User.objects.iterator():
122 for x in range(self.objects_with_perms_count):
123 obj = self.Model.objects.get(id=random.choice(ids))
124 self.grant_perm(user, obj, self.perm)
125
126 def grant_perm(self, user, obj, perm):
127 assign_perm(perm, user, obj)
128
129 @Timed("Check permissions")
130 def check_perms(self):
131 ids = range(1, self.objects_count)
132 for user in User.objects.iterator():
133 for x in range(self.objects_with_perms_count):
134 obj = self.Model.objects.get(id=random.choice(ids))
135 self.check_perm(user, obj, self.perm)
136
137 @Timed("Get objects")
138 def get_objects(self):
139 ctype = ContentType.objects.get_for_model(self.Model)
140 ids = range(1, self.users_count)
141 for user in User.objects.iterator():
142 for x in range(self.objects_with_perms_count):
143 filters = {"user": random.choice(ids), "permission__codename__in": [self.perm], "content_type": ctype}
144 qs = UserObjectPermission.objects.filter(**filters).all()
145 if not self.subquery:
146 qs = [v.object_pk for v in qs]
147 list(self.Model.objects.filter(id__in=qs))
148
149 def check_perm(self, user, obj, perm):
150 user.has_perm(perm, obj)
151
152 @Timed("Benchmark")
153 def main(self):
154 self.info("=" * 80)
155 self.info(self.name.center(80))
156 self.info("=" * 80)
157 self.prepare_db()
158 self.create_users()
159 self.create_objects()
160 self.grant_perms()
161 self.check_perms()
162 if not isinstance(self.Model, TestModel):
163 self.get_objects()
164
165
166 def main():
167 show_settings(settings, "benchmarks")
168 glob = [USERS_COUNT, OBJECTS_COUNT, OBJECTS_WIHT_PERMS_COUNT]
169 Benchmark("Direct relations benchmark with subqueries", *glob, model=TestDirectModel, subquery=True).main()
170
171 Benchmark("Direct relations benchmark without subqueries", *glob, model=TestDirectModel, subquery=False).main()
172
173 Benchmark("Generic relations benchmark without subqueries", *glob, model=TestModel, subquery=False).main()
174
175
176 if __name__ == "__main__":
177 main()