Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I'm trying to reuse the output of the time-consuming function in other functions without re-run it again. example:

%%time

def func1():

    sleep(100)

    y = 123

    return y

func1()

Wall time: 100 s

%%time 

def func2():

    x = func1()

    return x

func2()

Wall time: 100 s

I want func2 to reuse my output of fun1 without waiting for another 100 all over again. 

1 Answer

0 votes
by (36.8k points)

You can use the functools.lru_cache for a task:

from time import sleep

from functools import lru_cache

@lru_cache

def func1():

    sleep(3)

    y = 123

    return y

print(func1())  # <-- this waits 3 seconds

print(func1())  # <-- this is printed immediately

Want to be a master in Data Science? Enroll in this Data Scientist

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...