Created
June 19, 2022 19:40
-
-
Save VedAustin/e52a2e3f14b0e9eb084e1a8ee2015cb3 to your computer and use it in GitHub Desktop.
Perfomance improvement using slots
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
import timeit | |
from dataclasses import dataclass | |
from functools import partial | |
from statistics import median | |
logging.basicConfig(level=logging.INFO) | |
@dataclass(slots=True) | |
class SchoolSlots: | |
name: str | |
rating: str | |
students: int | |
@dataclass(slots=False) | |
class School: | |
name: str | |
rating: str | |
students: int | |
def get_set(school: School | SchoolSlots): | |
_ = school.name | |
school.name = "No Name" | |
_ = school.name | |
def main(): | |
wo_slots = School("Name 1", "A", 1000) | |
w_slots = SchoolSlots("Name 2", "A+", 1000) | |
no_slots_stat = median(timeit.repeat(partial(get_set, wo_slots), number=10 ** 6)) | |
with_slots_stat = median(timeit.repeat(partial(get_set, w_slots), number=10 ** 6)) | |
logging.info(f"Average improvement: {(no_slots_stat - with_slots_stat) * 100 / no_slots_stat}") | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment