Soma
Soma

Reputation: 743

how is it possible to run a code in limited time?

Is it possible to run a code in an interval of time? for example, there is a small function as follow:

   function test(n)
     A = rand(n, n)
     b = rand(n)
   end

How is it possible test code will be run for 5 second and then it will be stopped?

would you please help me? Thanks very much.

Upvotes: 0

Views: 194

Answers (1)

logankilpatrick
logankilpatrick

Reputation: 14521

Here is what you could do:


function test(n)
     A = rand(n, n)
     b = rand(n)
end

start_time = time_ns() #Gets current time in nano seconds
seconds = 5000000000 #converted 5 seconds to nano seconds. 

@time begin
    while time_ns() - start_time <= seconds:  
        test(1)
    end

end
#Note this code is designed to provide the logic of implementing this idea and may or may not work in your case. 

The hard part about this that I mentioned in my comment is all time-based things in programming are best effort cases and not absolute.

See some examples from the docs about time for reference or my example below:

julia> @time begin
           sleep(0.3)
       end
  0.305428 seconds (9 allocations: 352 bytes)

julia> 

Even though we said we wanted to sleep for 0.3 seconds, it really slept for ~0.305 seconds. This should hopefully illuminate the issue with trying to do this.

It may also be possible depending on what you are doing to use threads. If you only want to give a function 5 seconds to return a new value, you can call that function with a thread, and then check the variable that accepts the return value to see if it's been updated. If it hasn't in 5 seconds, you can kill the thread or move on potentially. Though, I am not 100% sure of this.

Upvotes: 2

Related Questions