Panel | Tutorial 12 Performance and Debugging (Multithreading Unfinished)

2023/02/21 09:05 AM posted in  Coding Notes   comments
Tags:  #Panel

some of the best practices to debug your applications and profile your application to maximize performance.

Caching

Panel's global state object, can be directly assigned to pn.state.cache. using the pn.state.as_cached helper function or the pn.cache decorator.

Manual Usage

if 'data' in pn.state.cache:
    data = pn.state.cache['data']
else:
    pn.state.cache['data'] = data = ... # Load some data or perform an expensive computation

pn.cache Decorator

@pn.cache(max_items=10, policy='LRU')
def load_data(path):
    return ... # Load some data

Caching in Memory

select = pn.widgets.Select(options={
    'Penguins': 'https://raw.githubusercontent.com/mwaskom/seaborn-data/master/penguins.csv',
    'Diamonds': 'https://raw.githubusercontent.com/mwaskom/seaborn-data/master/diamonds.csv',
    'Titanic': 'https://raw.githubusercontent.com/mwaskom/seaborn-data/master/titanic.csv',
    'MPG': 'https://raw.githubusercontent.com/mwaskom/seaborn-data/master/mpg.csv'
})

# The pn.cache decorator can easily be combined with pn.bind 
@pn.cache
def fetch_data(url):
    return pd.read_csv(url)

pn.Column(select, pn.bind(pn.widgets.Tabulator, pn.bind(fetch_data, select), page_size=10))

Disk Caching

Make use of disck caching if server will be restarted.
setting to_disk=True

Clear the Cache

Once a function has been decorated with pn.cache you can easily clear the cache by calling .clear() on that function, e.g. in the example above you could call load_data.clear(). If you want to clear all caches you may also call pn.state.clear_caches().