1. 如何在python中使用時間限制進行緩存
可以試試裝飾器
defcache(fn=None,time_to_live=3600*24):#oneDAYdefault(orwhatever)
ifnotfn:returnfunctools.partial(cache,time_to_live=time_to_live)
my_cache={}
def_inner_fn(*args,**kwargs)
kws=sorted(kwargs.items())#inpython3.6+youdontneedsorted
key=tuple(args)+tuple(kw)
ifkeynotinmy_cacheortime.time()>my_cache[key]['expires']:
my_cache[key]={"value":fn(*args,**kwargs),"expires":time.time()+time_to_live}
returnmy_cache[key]
return__inner_fn
@cache(time_to_live=3600)#anhour
defmy_sqrt(x):
returnx**0.5@cache(time_to_live=60*30)#30mins
defget_new_emails():
returnmy_stmp.get_email_count()
2. python怎麼讓輸出不緩存,立即輸出
linux上是有緩存機制的,輸出緩存(即所謂的行緩沖區)是根據換行符來寫數據的,看到換行符,就會從緩存寫到磁碟。或者你也可以強制flush。
3. python 如何釋放緩存
我覺得可能是因為你的py文件在第一次啟動後,已經編譯成pyc文件了,再次啟動的時候都是載入pyc,省去了編譯的階段,所以速度很快。
你可以試著把程序目錄下的所有pyc或者你的代碼文件對應的pyc文件刪除,看看是不是可以和第一次載入速度相同
4. python有緩存模塊嗎
從Python 3.2開始,可以使用functools庫中的裝飾器@lru_cache。這是最近使用過的緩存,所以其中的項目沒有到期時間,但作為快速入侵,它非常有用。
from functools import lru_cache
@lru_cache(maxsize=256)def f(x):
return x*xfor x in range(20):
print f(x)for x in range(20):
print f(x)
5. python threading.local 有緩存嗎
#coding=utf-8
import threading
# 創建全局ThreadLocal對象:
localVal = threading.local()
localVal.val = "Main-Thread"
def process_student():
print '%s (in %s)' % (localVal.val, threading.current_thread().name)
def process_thread(name):
#賦值
localVal.val = name
process_student()
t1 = threading.Thread(target= process_thread, args=('One',), name='Thread-A')
t2 = threading.Thread(target= process_thread, args=('Two',), name='Thread-B')
t1.start()
t2.start()
t1.join()
t2.join()
print localVal.val