# TimeConstrained for parallel computations

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?

-

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

-
{"extraction_info": {"found_math": true, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 1, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0, "math_score": 0.17451906204223633, "perplexity": 3662.856774475372}, "config": {"markdown_headings": true, "markdown_code": true, "boilerplate_config": {"ratio_threshold": 0.18, "absolute_threshold": 10, "end_threshold": 15, "enable": true}, "remove_buttons": true, "remove_image_figures": true, "remove_link_clusters": true, "table_config": {"min_rows": 2, "min_cols": 3, "format": "plain"}, "remove_chinese": true, "remove_edit_buttons": true, "extract_latex": true}, "warc_path": "s3://commoncrawl/crawl-data/CC-MAIN-2015-27/segments/1435375635604.22/warc/CC-MAIN-20150627032715-00251-ip-10-179-60-89.ec2.internal.warc.gz"}