Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

The Mathematica manual states

TimeConstrained takes account only of CPU time spent inside the main Mathematica kernel process; it does not include additional threads or processes.

However, my computation involves a parallel computation. As an example, consider the code

count = 0;
SetSharedVariable[count];
ProgressIndicator[Dynamic[count], {0, 500}]

f = Total[ParallelTable[count++; i^2, {i, 1, 500}]];

TimeConstrained[f, .1, "fail"]

(* 41791750 *)

How can I achieve that "fail" is returned. I can imagine that it could be complicated to compute the total CPU time of all sub-processes, but for my application it would be sufficient to consider the absolute amount of real-time that has passed as AbsoluteTiming[] does.

Any suggestions?

share|improve this question

1 Answer 1

up vote 0 down vote accepted

You should change

f = Total[ParallelTable[count++; i^2, {i, 1, 500}]];

into

f := (count = 0; Total[ParallelTable[count++; i^2, {i, 1, 500}]]);

Then, at least in Mathematica v.9, it works.

The fact is that f must be calculated only inside TimeConstrained and not before. The counter must be zeroed before any parallel evaluation

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.