HannWindow implementation and discretization speed

I would like to discretize a series of HannWindows, but two issues arise. First, my manual implementation of HannWindow seems to discretize faster than the built-in function. Second, the discretization in both cases is slow.

I begin by defining variables which give the Hann windows each different widths and locations:

{hmax, sbase, mcoeff, mmax, kmax, hf} = {30, 468, 2, 237, 10, 2};
{hbc, hb, hwf} = {2, 60, 100};
len = 2401;

Do[widthbuffer[n] = hbc*n + hb;
hw[n] = ((8*n + hwf)/2 + widthbuffer[n]), {n, 1, hmax}]


Then I construct a set of functions, indexed by k and m, each of which is a series of Hann windows. Using the built-in function:

Do[sep = sbase + mcoeff*m;
Do[hc[n] = 222 + (n - 1)*sep + (-1 + 2 k/kmax)*706/10, {n, hf,hmax}];
hannM[k][m] = Sum[HannWindow[(t - hc[n])/(2 hw[n])], {n, hf, hmax}],
{k, 0,kmax}, {m, 1, mmax}]

(* 1.52106s *)


If I manually implement the HannWindow, the timing is slightly different:

Do[sep = (sbase + mcoeff*m);
Do[hc[n] = 222 + (n - 1)*sep + (-1 + (2*k/kmax))*(706/10);
harg[n] = (t - hc[n])/(2 hw[n]); hl[n] = hc[n] - hw[n];
hr[n] = hc[n] + hw[n];
hann[n] =
Piecewise[{{0.5 + 0.5*Cos[2 Pi*harg[n]],
hl[n] <= t <= hr[n]}}], {n, hf, hmax}];
hannc[k][m] = Sum[hann[n], {n, hf, hmax}], {m, 1, mmax}, {k, 0,kmax}]

(* 1.77596s *)


Now, discretizing for k=0 and m=1, for example, shows very different timings. Using the built-in HannWindow:

hMT = Table[hannM[0][1], {t, len}];

(* 0.441911s *)


Using my manual implementation:

hcT = Table[hannc[0][1], {t, len}];

(* 0.056057s *)


What accounts for the difference in speed between these two methods, and is there a way to speed up the discretization, which for both cases seems to be slow?

• hannc[0][1] is a function defined by Piecewise. That can easily be compiled by Table while HannWindow is probably not compilable. – Henrik Schumacher Jun 7 '18 at 16:10
• In the documentation it looks like HannWindow is defined Piecewise. I suppose there must be an additional feature which is slowing it down. – Questino Jun 8 '18 at 13:21
• Did you check how fast it is when you apply FunctionExpand to HannWindow? – Lukas Lang Jun 8 '18 at 21:56
• @Mathe172 Thanks for the suggestion. FunctionExpand reduces the discretization time by a factor of about 3.7, so that is an improvement over simply applying HannWindow. The manual method is still 2 times faster than this, however. – Questino Jun 11 '18 at 18:26