Created
June 8, 2015 06:50
-
-
Save mengzhuo/2fbaff790e6e9d786f34 to your computer and use it in GitHub Desktop.
Python 单例(singleton) 方式比拼
This file contains 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
#!/usr/bin/env python | |
# encoding: utf-8 | |
class Singleton(type): | |
def __init__(cls, name, bases, dict): | |
super(Singleton, cls).__init__(name, bases, dict) | |
cls.instance = None | |
def __call__(cls,*args,**kw): | |
if cls.instance is None: | |
cls.instance = super(Singleton, cls).__call__(*args, **kw) | |
return cls.instance | |
class MetaSingleton(object): | |
__metaclass__ = Singleton | |
counter = 1 | |
def get(self): | |
self.counter += 1 | |
return self.counter | |
class ModuleSingleton(object): | |
counter = 1 | |
def get(self): | |
self.counter += 1 | |
return self.counter | |
m = ModuleSingleton() | |
def singleton(cls): | |
instances = {} | |
def getinstance(): | |
if cls not in instances: | |
instances[cls] = cls() | |
return instances[cls] | |
return getinstance | |
@singleton | |
class DecoratorClass: | |
counter = 1 | |
def get(self): | |
self.counter += 1 | |
return self.counter |
This file contains 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
In [3]: %%timeit | |
singleton_test.m.get() | |
1000000 loops, best of 3: 367 ns per loop | |
In [4]: %%timeit | |
singleton_test.DecoratorClass().get() | |
1000000 loops, best of 3: 715 ns per loop | |
In [8]: %%timeit | |
singleton_test.MetaSingleton().get() | |
1000000 loops, best of 3: 727 ns per loop |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment