File: dict_vs_class_vs_namedtuple.py

package info (click to toggle)
python-pyperform 1.86-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 168 kB
  • sloc: python: 729; makefile: 17
file content (68 lines) | stat: -rw-r--r-- 1,721 bytes parent folder | download
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
__author__ = 'clobo'

from collections import namedtuple  #!
from pyperform import ComparisonBenchmark

MyNamedTuple = namedtuple('ButtonStatus', ('name', 'age', 'gender'))  #!


class MyClass(object):  #!
    __slots__ = ('name', 'age', 'gender')

    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender


'''''''''''''''''''''''''''''''''''''''''''''''''''''''''
                     Creation Speed Tests
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''


@ComparisonBenchmark('class')
def create_class():
    for i in xrange(1000):
        c = MyClass('calvin', 25, 'male')


@ComparisonBenchmark('class')
def create_namedtuple():
    for i in xrange(1000):
        c = MyNamedTuple('calvin', 25, 'male')


@ComparisonBenchmark('class')
def create_dict():
    for i in xrange(1000):
        c = {'name': 'calvin', 'age': 25, 'gender': 'male'}


'''''''''''''''''''''''''''''''''''''''''''''''''''''''''
                    Lookup Speed Tests
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''


@ComparisonBenchmark('lookup')
def class_attr_lookup():
    c = MyClass('calvin', 25, 'male')
    for i in xrange(10000):
        name, age, gender = c.name, c.age, c.gender


@ComparisonBenchmark('lookup')
def namedtuple_attr_lookup():
    c = MyNamedTuple('calvin', 25, 'male')
    for i in xrange(10000):
        name, age, gender = c.name, c.age, c.gender


@ComparisonBenchmark('lookup')
def dict_attr_lookup():
    c = {'name': 'calvin', 'age': 25, 'gender': 'male'}
    for i in xrange(10000):
        name, age, gender = c['name'], c['age'], c['gender']


ComparisonBenchmark.summarize('class')
ComparisonBenchmark.summarize('lookup')