Computation with time limit

后端 未结 9 2397
你的背包
你的背包 2021-01-02 12:08

I\'m trying to write a construct which allows me to run computations in a given time window. Something like:

def expensiveComputation(): Double = //... some          


        
9条回答
  •  北荒
    北荒 (楼主)
    2021-01-02 12:48

    In the currentThread?? Phhhew... Check after each step in computation Well if your "expensive computation" can be broken up into multiple steps or has iterative logic you could capture the time when you start and then check periodically between your steps. This is by no means a generic solution but will work.

    For a more generic solution you might make use of aspects or annotation processing, that automatically litters your code with these checks. If the "check" tells you that your time is up return None.

    Ill ponder a solution in java quickly below using annotations and an annotation processor...

    public abstract Answer{}
    public class Some extends Answer {public Answer(double answer){answer=answer}Double answer = null;}
    public class None extends Answer {}
    
    
    //This is the method before annotation processing
    @TimeLimit(45)
    public Answer CalculateQuestionToAnswerOf42() {
     double fairydust = Math.Pi * 1.618;
     double moonshadowdrops = (222.21) ^5;
     double thedevil == 222*3;
     return new Answer(fairydust + moonshadowdrops + thedevil);
    }
    
    //After annotation processing
    public Answer calculateQuestionToAnswerOf42() {
     Date start = new Date() // added via annotation processing;
     double fairydust = Math.Pi * 1.618; 
     if(checkTimeout(start, 45)) return None; // added via annotation processing;
     double moonshadowdrops = (222.21) ^5;
     if(checkTimeout(start, 45)) return None; // added via annotation processing;
     double thedevil == 222*3;
     if(checkTimeout(start, 45)) return None; // added via annotation processing;
     return new Answer(fairydust + moonshadowdrops + thedevil);
    }
    

提交回复
热议问题