# Use Compile to speed up evaluation

I have read, that using Compile command can speed up evaluations in mathematica. I have a mathematical expression, which I evaluate using following command:

n = 5000
k = 10
c = n/k
a = Floor[n* Log]
b = a + 1
pk1 = Table[
Sum[Binomial[a, i]*StirlingS2[i, r]*(n - c)^(-i), {i, r, a}], {r,
1, c - 1}];


I was trying to use Compile to evaluate this, but I don't know how to 'tell' Compile that I want to evaluate for range {r,1,c-1}, I just made:

cf = Compile[{?},
Sum[Binomial[a, i]*StirlingS2[i, r]*(n - c)^(-i), {i, r, a}]]


Can someone suggest how I should transmor my comment to compile commend? Or how I can speed up my evaluations in different way?

• You need to look at this: mathematica.stackexchange.com/questions/1096/… - you'll see that Binomial and StirlingS2 cannot be compiled, so you are unlikely to benefit from compilation. – dr.blochwave Nov 4 '14 at 9:23
• ParallelTable may speed up a bit. As well as putting n=5000. and not n=5000 – Rolf Mertig Nov 4 '14 at 22:33

As mentioned by blochwave, your code can't benefit from compilation. To speed up your code, take Rolf Mertig's advise may be the best. Making use of the Listable attribute of those arithmetical function will also help a little:

(* Tested under n = 1000, dual-core laptop *)
pk1 = Table[
Sum[Binomial[a, i]*StirlingS2[i, r]*(n - c)^(-i), {i, r, a}], {r, 1, c - 1}]; //
AbsoluteTiming

{44.5980000, Null}

pk2 = ParallelTable[
Sum[Binomial[a, i]*StirlingS2[i, r]*(n - c)^(-i), {i, r, a}], {r, 1, c - 1}]; //
AbsoluteTiming

{22.5580000, Null}

pk3 = ParallelTable[
With[{i = Range[r, a]},
Total[Binomial[a, i] StirlingS2[i, r] (n - c)^(-i)]], {r, c - 1}]; //
AbsoluteTiming

pk1 == pk2 == pk3

{17.4624000, Null}
True