6
$\begingroup$

Trace and TracePrint generates or prints a list of all expressions used in the evaluation of its argument. For complicated expressions that can be thousands of lines. Large Trace tasks can be very slow and even crash the kernel.

How can one TracePrint directly to a text file?

$\endgroup$

1 Answer 1

6
$\begingroup$

This will call TraceScan and save each line (WriteLine) to a text file.

A time-out can be defined (default 1 minute), and the function returns a clickable File for seamless opening.

ClearAll[TraceToFile] SetAttributes[TraceToFile, HoldFirst] TraceToFile[expr_, filename_String, timeout_: 60] := With[ { file = OpenWrite[filename] }, Echo[timeout, "Timeout: "]; Echo[FileNameJoin[{Directory[], filename}], "File: "]; Echo[ToString[Hold[expr], InputForm], "Expresion"]; TimeConstrained[ TraceScan[ WriteLine[ file, StringTake[ToString[#, InputForm], {10, -2}] ] &, expr ], timeout]; Close[file]; File[FileNameJoin[{Directory[], filename}]] ] 

Example

fib[0] = fib[1] = 1; fib[n_] := fib[n - 1] + fib[n - 2]; First@AbsoluteTiming[TracePrint[fib[12]]] (* 20.8437 *) First@AbsoluteTiming@TraceToFile[fib[12], "TraceTest.txt"] (* 0.320829 *) 

Mathematica graphics

Mathematica graphics

$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.