Felipe Endlich
Felipe Endlich

Reputation: 620

How to run an algorithm only for a time in python

So, Let's say I want to do endless calculations and in a given moment I want to stop the algorithm and get the result at that time. How can I do that in python?

For example, imagine that function running for 10 secs, is there a way that I can get the value of x?

class MyClass():
  def __init__(self, x):
    self.__x = x

  def inititySum(self):
    while(True):
      self.__x += 1

A = MyClass(0)
A.infinitySum()

Upvotes: 0

Views: 38

Answers (1)

Mohd
Mohd

Reputation: 5613

You can use multiprocessing and initialize a Process to run the function then you can get the value of x whenever you want, and make sure you terminate() the process or you will reach integer overflow. However, when using multiprocessing different processes don't share variables so you have to initialize your x as a shared variable between processes. For example:

import multiprocessing
import time

class MyClass:

    def __init__(self, x):
        self.x = multiprocessing.Value('i', x)

    def infinitySum(self):
        while True:
            self.x.value += 1

A = MyClass(0)
p = multiprocessing.Process(target=A.infinitySum)
p.start()
time.sleep(5)
p.terminate()
print(A.x.value) # output: 3834689

Upvotes: 1

Related Questions