# Tag Info

## Hot answers tagged performance-tuning

17

I guess I should not have been surprised that there are actually many ways to estimate the Gaussian and mean curvature of a triangular mesh. I shall present here a slightly compacted implementation of the MDSB method, with a few of my own wrinkles added in. I should say outright that the current implementation has two weaknesses: the determination of the ...

14

It took me a while, but the suggestion of @Michael E2 was quite helpful, and especially the post (Optimize inner loops). For those of you (like me) who are new to this style of programming in Mathematica there are a few things that helped in my particular example. In my slow version I was looping over all vertices in the mesh list. For example in ...

10

I would like to link this W Community thread here where I asked for functionality like this in 2015 September, and explained why it's critical to have it. I can't link to individual posts but you can find it by searching the page for "StringToDouble". As Leonid mentioned, there is InternalStringToDouble. This function is very fast, but it does not ...

9

The reason for that is that MN is numerical, since you have 0.5 in it. So in the Do loop, every step is done just numerically. In refl1 the MatrixPower is analytically performed and converted to numerical just as last step. If you change the MatrixPower input also to a numerical input the execution times is much faster with the MatrixPower function. refl3[...

7

Code Using the very fast function intervals from this post by Mr.Wizard, intervals[a_List] := {a[[Prepend[# + 1, 1]]], a[[Append[#, -1]]]}\[Transpose] &@ SparseArray[Differences@a, Automatic, 1]["AdjacencyLists"] We can write: negativePositions[lst_] := intervals[ Flatten@SparseArray[UnitStep[lst], Automatic, 1]["NonzeroPositions"] ...

5

You may be going to too much trouble here. Consider that Position works on a matrix just as well as a vector. You did not include values for your parameters, so I can't use your code, but take a look at the following example. I have a matrix selector that contains $0$ or $1$ entries, and I want to grab the elements of another matrix target that correspond ...

5

This will compile just fine, though as others have said, Compile is a tricky beast. One key thing to remember is adding 0.0 I to your initialization of M, otherwise you will get a Compile::cset error message. compiledrRefl = Compile[{{λ, _Real}, {d1, _Real}, {d2, _Real}, {n1, _Complex}, {n2, _Complex}, {Np, _Integer}}, ...

4

Your solution doesn't seem to work when there are duplicates. Anyway, could you test the performance of the following method? example = RandomChoice[{"Clothing", "Clothing/Accessories", "Clothing/Accessories/Belts", "Watch", "Watches/Accessories", "Watches/Accessories/Pocket Watch Chains" }, 15000 ]; Split[Sort@example, StringStartsQ[#2, #] &...

4

Get the relation graph of your example graph = SimpleGraph[RelationGraph[StringStartsQ, example], VertexLabels -> "Name"] Get the end of the vertex in every weaky connected graph First@*TopologicalSort/@WeaklyConnectedGraphComponents[graph] {"Clothing/Accessories/Belts", "Watches/Accessories/Pocket Watch Chains"} Hope this can help. :)

4

Use memoization. See here for a description of the memoization in general, and here for its Mathematica implementation. This will avoid having to recalculate all the previous values to determine the next one: Clear[x, T, a, b] T[x_] := T[x] = Piecewise[{{1 - x, 0 <= x < 1/7}, {(x + 6)/7, 1/7 <= x <= 1}}] a[n_] := a[n] = n/(n + 5)^5 b[n_] := b[n] ...

4

One can use the new function DistanceMatrix[] for the purpose; this avoids repeated computations (since the underlying matrix is symmetric). With[{stepSize = 2, end = TMax}, MatrixPlot[UnitStep[0.01 - DistanceMatrix[uSolpbc[Range[0, end, stepSize], 0]]]]] and your plot is produced very quickly, without the need to invoke parallelization.

4

Import and ImportString handle the e number format okay. You might be able to Import directly from file, or use ImportString to process the data you've already read in: res = fromReadList ~StringRiffle~ "\n" ~ImportString~ "TSV" ~Cases~ {__,"Cake"|"Cookies",_};

3

It is because you are using exact numbers. Use floating number instead. Like Timing[Do[refl1[100., 2., 3., 5., 6., 100.], {100}]] Timing[Do[refl2[100., 2., 3., 5., 6., 100.], {100}]] {0.012001, Null} {0.016001, Null} which is the counter example of your counter intuition :)

3

Thanks to the recent post by ilian who uncovered and explained the undocumented OptimizationFindFitObjectiveFunction, I have found OptimizationFindFitResidualFunction which seems to be ideally suited to the original goals of the question. With the latter we don't even need to construct the residual vector explicitly, we just specify the model function ...

3

EDIT: My original answer, while quite a bit quicker than the current answer, dropped some words that should not be dropped, as does the other current answer, e.g.. {"pa","paperweight"} fails on both (unless that is the intent of the OP, which I doubt). This led me to the following, which does not suffer from the problem and is also quite a bit quicker yet: ...

3

This is essentially the same algorithm as Leonid's but implemented in terms of Pick instead of sparse arrays: negativePositions2[lst_] := Module[{a, b}, a = Pick[Range[Length[lst]], UnitStep[lst], 0]; b = UnitStep[Differences[a]~Subtract~2]; Transpose[{Pick[a, b~Prepend~1, 1], Pick[a, b~Append~1, 1]}]]

3

Leonid's answer is as impressive as it is too advanced for me (a lot). For lesser mortals like me, not as fast but still acceptable performance: largeTest = RandomInteger[{-100,100},1000000]; a quarter of a second performance for a million length list: Transpose[{#, Append[Rest[# - 1], Length@#]}] & [FoldList[Plus, 1, Length /@ Split@Sign@...

2

This is not an answer but a comment on the speed issue @J.M. mentioned: One thing that can be done is to use Needs["NDSolveFEM`"] bmesh = ToBoundaryMesh[r, {{-1.1, 1.1}, {-1.1, 1.1}, {-1., 1.}}, MaxCellMeasure -> {"Length" -> 0.1}]; (* bmesh = ToBoundaryMesh[dod] *) pts = bmesh["Coordinates"]; tri = Join @@ ElementIncidents[bmesh["...

2

Here is a simple and universal function which formats timings (for real-time monitoring of elapsed time one should replace Round with Floor): formatTiming = StringJoin[{If[# >= 100, ToString@#, IntegerString[#, 10, 2]] &@Floor[#/3600], ":", IntegerString[Floor[Mod[#, 3600]/60], 10, 2], ":", IntegerString[Mod[#, 60], 10, 2]} &@...

2

Number counting approach Since your file contains (with rare exceptions) only 3 numbers on each line and the data has dimensions {400,4001,2}, it is possible to calculate how many lines you should read in order to obtain the first 40 sets out of 400. At first, some checks: data = << "EigF-V1_1.0-V2_0.000.txt"; Dimensions[data] {400, 4001, 2} ...

2

The most I've managed to improve the speed is about a factor of 2, but I thought I would share my attempt anyhow. First, let's just compute the identity matrix once, instead of once each iteration step: id = SparseArray[IdentityMatrix[2n]]; Second, since we are going to need all the powers of both A1 and A2, we can gain some speed by simply bumping the ...

2

Since your Target is to save them for being protected from unintentional events I propose a different strategy, but check first, NumberForm NumberMarks Machine‐Precision Numbers vals = RandomReal[{-1, 1}, {12, 3}] NB copied as Plain Text {{0.768526,0.981104,-0.384388},{0.177151,0.378702,0.537739},{0.338071,0.100119,0.548224},{-0.374293,0.472408,-0....

2

Perhaps, ClearAll[inpField] inpField[arg_, fs_: 5] := InputField[arg, FieldSize -> fs, Background -> Yellow, Appearance -> "Frameless"] Interpretation[{f = {-y, -2 x}, xmin = 0, xmax = 1, ymin = 0, ymax = 1}, Panel@Row[{"StreamPlot[", inpField[Dynamic[f], 12], ", \n ", Invisible["StreamPlo"], "{x, ", inpField[Dynamic[xmin]], ",", ...

2

The plot in the question must have been obtained with stepSize = 15, not stepSize = 2. Using the latter value gives a smooth plot, The computation takes about 78 sec on my PC. To address the specific issue in the question, the run time can be reduced by two orders of magnitude using Block[{stepSize = 2, end = TMax, tt, rd}, tSolpbc = Table[uSolpbc[...

2

Where can the code be improved? First of all: Try to avoid loops (Do, For, While) where possible - they're usually much more verbose than functional alternatives. Second: Read the documentation. ComponentMeasurements can take a list of measurements, and will then return a list of values for each component. Third: Use functions to encapsulate units of ...

1

img = Import["http://i.stack.imgur.com/bkNTj.png"]; pos = ComponentMeasurements[img// Binarize, {"Centroid", "EquivalentDiskRadius"}][[All, 2, 1]]; Length[pos] Show[img, Graphics[{Red, Circle[#, 10]} & /@ pos]] 3 You might be interested in Count flowers in an image and Count Elements in Image. For your complete folder, SetDirectory[...

1

PrecisionGoal -> 10 gives an error of -0.470581 in the weight. Automatic Gives the precision goal of half of MachinePrecision, that doesn't mean it's optimized for your calculation. When you have high error, precision is the first you look at, so incrementally increasing precision can help. It's possible that adding 2nd derivative limits the amount of ...

1

With ver 10.4.1, I am unable to evaluate dNdz[0, 12] using the code provided in the question, instead getting the error message, NIntegrate::inumr: The integrand ddndLogMdz[0,var] has evaluated to non-numerical values for all sampling points in the region with boundaries {{12,20}}. >> This occurs because the derivatives of delta and Sigma are undefined....

1

If you want to substitute 1/x->0 in in expressions then take the limit x->Infinity: y = (10+2*x)/x; Limit[y, x->Infinity] Other ways of doing that is the followings (see bbgodfrey's comment): First@Collect[y, x] Coefficient[y, x, 0]

1

Here, I will use LibraryLink technique to calculate the nonzero B-spline basis. About the C code, please see happy fish's revision. Firstly, I make a comparison with optimizedNonzeroBasis[], compiledNonzeroBasis[] and librarylinkNonzeroBasis[]. knots0 = Join[ConstantArray[0, 3001], Range[1, 5000], ConstantArray[5001, 3001]]; deg0 = 3000; i = 3002; ...

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