I would like to define a function func
using a combination of built in functions and obtain a similar speed in evaluation as if I evaluated those built in functions by themselves. Currently I am seeing a slow down. An example:
K[x_] = ConstantArray[func[x], {100, 100}];
K2[x_] = ConstantArray[Sin[x], {100, 100}];
func[x_] = Sin[x];
AbsoluteTiming[K[1.]]
AbsoluteTiming[K2[1.]]
{0.00953596, {...}}
{0.00413393, {...}}
The matrix K2
evaluates significantly faster if I replace func
by Sin
, even though func
is defined to be an alias of Sin
.
My questions:
- What internal process leads to this time difference?
- How can I define
func
such that the times are comparable?
K2[x_] = ConstantArray[Sin[x], {100, 100}];
you will evaluateSin
10000 times for each call toK2
. UseSetDelayed
i.e.K2[x_] := ConstantArray[Sin[x], {100, 100}];
$\endgroup$ – Coolwater Nov 25 '17 at 18:15K
andK2
are somehow representative for a large matrix with many built in functions that need to be evaluated. I want to keep theSet
here and understand where the speed up comes from $\endgroup$ – Mr Puh Nov 25 '17 at 18:24K
it takes 2 top-level calls to compute each entry. InK2
there is only 1 top-level call, so you should expect the time difference. If you change the 3rd line tofunc = Sin;
the pattern matcher is skipped in the second call which makes the difference smaller. $\endgroup$ – Coolwater Nov 25 '17 at 18:33x
? The actual matrix has dimension 1000x1000 and has no equal entries and evaluatesfunc
at different points. $\endgroup$ – Mr Puh Nov 25 '17 at 18:48