Streamlit Cache
There are times when you might have a function in your app that is computationally expensive. Streamlit provides a means through the st.cache() method to save on this expense. When set up, it ensures that the value stored in cache is what is used by your app, thus negating the need to calculate the value each time the function is run.
The only time a new value is calculated is if one of the following things happens:
Function input parameters change
Function body changes
Inner function changes
x = 200 y = 3000000
def non_cached_function(x, y): return x ** y
start = time() non_cached_function(x,y) duration = round((time() - start),3)
st.write(“Non-Cached Function took {} seconds to run”.format(duration))
@st.cache def cached_function(x, y): return x ** y
start = time() cached_function(x,y) duration = round((time() - start),3)
st.write(“Cached Function took {} seconds to run”.format(duration))
In the code above, the first time you execute it, both functions will take similar time to complete. The second time you execute it, the second function will take significantly less time to complete.
Create a free account to access the full course.
By signing up, you agree to Educative's Terms of Service and Privacy Policy