# Tag Info

36

You can put your Mathematica session in debug mode by going to Evaluation->Debugger Then, make some definitions and wrap the profiled code in RuntimeToolsProfile For example, in debug mode, run f[x_] := x^2 Table[f[x], {100000}]; // RuntimeToolsProfile and you get a nice As @acl mentioned in the comments, clicking in the gray area in the output ...

25

We are challenged to determine "how fast MMa can get" and, in so doing, to suggest rules "to choose different programming styles." The original solution takes 116 seconds (on my machine). At the time the question was posted, the solution time had been reduced by a factor of 1000 (10 doublings of speed) to 0.124 seconds by suggestions from users in chat. ...

22

Just a literal implementation of a formula for the day of the week: Clear[dow]; dow[{year_, month_, day_, _ : 0, _ : 0, _ : 0}] := Module[{Y = If[month == 1 || month == 2, year - 1, year], m = Mod[month + 9, 12] + 1, y, c, s = {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}}, y = Mod[Y, 100]; c = Quotient[Y, 100]; ...

21

I will provide one solution which will be using Java and a simple Java reloader I recently introduced. This solution brings to the table up to 100-fold speed-up for large lists of dates. Preparation I will borrow @Mike's functions to generate a random list of dates, from his code in his recent question RandomDateList[] := { RandomInteger[{1800, 2100}], ...

21

After some sleuthing through the xkcdConvert code I found the routine that is causing the execution slow down. The function containing the problem is the xkcdDistort function. See the following code: xkcdDistort[p_] := Module[{r, t, ix, iy}, r = ImagePad[Rasterize@p, 10, Padding -> White]; {ix, iy} = Table[RandomImage[{-1, 1}, ...

21

You can use GatherBy for this. You can map List onto Range[...] first if you wish to have exactly the same output you showed. positionDuplicates[list_] := GatherBy[Range@Length[list], list[[#]] &] list = {3, 3, 6, 11, 13, 13, 11, 1, 2, 3, 12, 8, 9, 9, 4, 15, 5, 6, 9, 12} positionDuplicates[list] (* ==> {{1, 2, 10}, {3, 18}, {4, 7}, {5, 6}, {8}, ...

20

The whole "fractal" is an exercise in rounding errors. Following all the links to some code, we find that something is considered an integer if its fractional part is less than 0.1. Using something similar to Mr.Wizard's answer: inQ = Abs[FractionalPart[N[#, 16]]] < 0.1 &; check[0 | 0., 0 | 0.] := 0; check[a_, b_] := With[{p = (a + b)/(a^2 + ...

20

You can implement an imperative-style circular buffer. big = Range@1*^7; size = Length@big; pointer = size; updateElement[new_Integer] := (pointer = 1 + Mod[pointer, size]; big[[pointer]] = new) Do[updateElement[RandomInteger@99], {100}] // AbsoluteTiming {0.000374, Null} To bring the buffer back to the normal form use big = RotateLeft[big, ...

20

Using Outer is here one of the worst methods, and not just because it computes the distance twice, but because you can't leverage vectorization in this approach. This is actually a common issue and an important point to stress: Outer works pairwise and is unable to utilize the possible vectorized nature of the operation it is performing on an ...

19

By the power of CUDALink and a CUDA-enabled GPU, this code drastically increases the speed of xkcdDistort by almost 120x. It takes circa 60s to transform a 400 × 400 image using xkcdDistort on my laptop (i5-2410M + NVIDIA GT540M + 4GB memory), and CUDAxkcdDistort can do the same in just 0.5s. Distortion of a 1000 × 1000 image takes just 2.5s. ...

16

Short answer Yes, it is possible to speed up the Delaunay-triangulation and make it as fast as it is in Matlab. If you are not afraid of some setup-work, then one possibility is to use a package which calls a c-implementation of the Delaunay-triangulation. One package I know is qh-math which is available in the Wolfram-library: This package includes ...

15

You can take advantage of listability. As a rule if a function has the Listable attribute listable operations will be faster than other alternatives such as mapping. {a, b, c} = Transpose[{a, b, c}]; Apply[Plus, x^a*y^b*z^c] or {a, b, c} = Transpose[{a, b, c}]; Total[x^a*y^b*z^c]

15

Here is another compiled implementation: hammingDistanceCompiled = Compile[{{nums, _Integer, 1}}, Block[{x = BitXor[nums[[1]], nums[[2]]], n = 0}, While[x > 0, x = BitAnd[x, x - 1]; n++]; n ], RuntimeAttributes -> Listable, Parallelization -> True, CompilationTarget -> "C", RuntimeOptions -> "Speed" ]; This appears to ...

14

This is done intentionally to update the plot quickly as you move the slider. Manipulate changes the setting for PerformanceGoal (via $PerformanceGoal) to "Speed" while you move the slider, then to "Quality" after you let go. This is seen in this simple demonstration: Manipulate[{n,$PerformanceGoal}, {n, 0, 1}] If you want the final quality while ...

13

I'll post a function based on the title of the question. You wrap your dynamic code in profileDynamics optionally passing the option "Print"->True (defaults to False). It should be noted that this can only profile the explicit Dynamics that are on the code. Nested dynamics that are generated at runtime are not profiled by this ClearAll[profileDynamics]; ...

13

I had a look at an evaluation copy of v9 today, and did some digging around in ImageValue. It looks like the main cause of the slowdown is the handling of Span notation in the position specification. ImageValue calls ImageImageDumpextractCoordinates with the requested position and the image dimensions as arguments. This function then does various checks ...

13

Here is a code that is about 2 orders of magnitude faster. We will use a finite element method to solve the issue at hand. Before we start, note however, that the transition between the Dirichlet values should be smooth. We use the finite element method because that works for general domains and some meshing utilities exist here and in the links there in. ...

13

edit: this doesn't really answer the question but merely provides some other alternatives, you should probably up-vote other more useful answers. There are also faster ways to do this using Pick or by compiling Select. Timing comparison done on a Macbook Air OS X 10.8.3 w/ 1.7 GHz Intel Core i5 with Mathematica 9.0.0.0. t = RandomInteger[100, 10^7]; ...

12

I've shown off Larsen's method before (and see this as well), but here it is as a formal answer: larsen[{yr_Integer, mo_Integer, da_Integer, ___}] := Module[{y = yr, m = mo, d = da, q}, If[m < 3, y--; m += 12]; q = d + 2 m + 1 + Quotient[3 (m + 1), 5] + y + Quotient[y, 4] + Quotient[y, 400] - Quotient[y, 100]; {Sunday, Monday, Tuesday, ...

12

If you are strictly interested in the number of trailing zeros in factorials $n!$, as the example in your question suggests, then consider the number of pairs of 2 and 5 in all the factors of numbers 1 through $n$. There is always a 2 to match a 5, so the number of fives gives the number of zeros. Integers divisible by 5 contribute one 5 to the total. ...

12

Experience working with distributions suggests analyzing the logarithm of the density function, rather than the density itself. Because the log is a monotonic increasing transformation, the mode of the log density occurs at the same value as the mode of the density. (This approach has general application, not just for beta distributions.) Let's develop ...

12

In this case Nearest simply has no code in place to use its fast octree approach with metrics other than Euclidean. This is, admittedly, a shame, because other $\ell_n$ spaces could in principle be supported in the same way. In particular $\ell_\infty$ (aka chessboard) is quite amenable to that underlying technology, but it just has not been implemented thus ...

12

I think it might be a good example for FindMinimum with the "PrincipalAxis" method. First define the summation function myfunc: Clear[myfunc] myfunc[n_?NumericQ] := NSum[1/(i + Sqrt[i]), {i, n // Round}] myfunc[n_?(# <= 0 &)] := 0 then the original problem can be solved by minimizing Abs[myfunc[n]-15]: sol = FindMinimum[Abs[myfunc[n] - 15], {n, ...

12

Looks like a computation that rightfully should be slow, you end up with close to 5 million sequences, and I suppose it's checking each constantly throughout to see if the products of the squares lead to square-able numbers. Why is Maple and Mupad faster? I can't say, but looking at the timing I would suspect they are just using approximate floats, leading ...

12

This seems to give a rather decent performance (final version with improvements by jVincent): Clear[getSubset]; getSubset[input_List,sub_List]:= Module[{inSubQ,sowMatches}, Scan[(inSubQ[#] := True)&,sub]; sowMatches[x_/;inSubQ@First@x] := Sow[x,First@x]; Apply[Sequence, Last@Reap[Scan[sowMatches, input], sub], {2}] ]; Benchmarks: n = ...

12

Here's a version with decent performance without Compile. The idea is to Transpose the data so that the vertex lists {{a,b},{b,c},{a,c}} can be created in one go instead of mapping over the list. The posh version of Flatten is used to reshape the list afterwards. trianglesToLinesSW[t_] := Union@Flatten[{{#1, #2}, {#2, #3}, {#1, #3}} & @@ ...

11

Here's an approach based on finding all right angled triangles with a hypotenuse <=500 and measuring the perimeters. The answer is the Commonest perimeter which is less than 1000. This runs in about 1 second. rats[n_] := DeleteDuplicates[ Cases[Divisors[n^2, GaussianIntegers -> True], z_Complex /; Abs[z] == n :> Sort[{Re@z, Im@z, n}]]]; ...

11

This will not scale to dimension 100 but will be an improvement on what you now have. It is cribbed from the section "Linear Algebra over Galois Fields here as well as the section "Groebner bases over modules and related computations" in this notebook. deg = 12; flen = 3; j = 0; While[flen > 2 && j++ < 100, defpoly = x^deg + 1 + ...

11

I was able to get 50x speedup w.r.t. your fastest code by using highly optimized Java buffered read functionality. The idea The idea is quite simple: use buffered read to reduce the IO overhead, and use Java to reduce the symbolic Mathematica overhead. Implementation You will have to run the Java reloader. Then, you call JCompileLoad@" import ...

10

Here's a reorganization of GaussianRandomField[] that works for any valid dimension, without the use of casework: GaussianRandomField[size : (_Integer?Positive) : 256, dim : (_Integer?Positive) : 2, Pk_: Function[k, k^-3]] := Module[{Pkn, fftIndgen, noise, amplitude, s2}, Pkn = Compile[{{vec, _Real, 1}}, With[{nrm = Norm[vec]}, ...

Only top voted, non community-wiki answers of a minimum length are eligible