Skip to content

Instantly share code, notes, and snippets.

@mengzhuo
Created June 8, 2015 06:50
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mengzhuo/2fbaff790e6e9d786f34 to your computer and use it in GitHub Desktop.
Save mengzhuo/2fbaff790e6e9d786f34 to your computer and use it in GitHub Desktop.
Python 单例(singleton) 方式比拼
#!/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
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