Skip to content

Instantly share code, notes, and snippets.

@ajasja
Created April 5, 2012 16:26
Show Gist options
  • Save ajasja/2312325 to your computer and use it in GitHub Desktop.
Save ajasja/2312325 to your computer and use it in GitHub Desktop.
(*Original implementation*)
MakeInPeriodicCellOrig =
Compile[{x, cellwidth},
First@Sort[{x, x - cellwidth, x + cellwidth},
Abs[#1] < Abs[#2] &], {{Sort[_], _Real}},
CompilationOptions -> {"ExpressionOptimization" -> True,
"InlineCompiledFunctions" -> True,
"InlineExternalDefinitions" -> True},
RuntimeAttributes -> {Listable},
"RuntimeOptions" -> "Speed"
];
(*my revritten*)
MakeInPeriodicCellImp = Compile[{x, cellwidth},
With[{ l = {x, x - cellwidth, x + cellwidth}},
Sort[Transpose[{Abs[l], l}]][[1, 2]]
], CompilationOptions -> {"ExpressionOptimization" -> True,
"InlineCompiledFunctions" -> True,
"InlineExternalDefinitions" -> True},
RuntimeAttributes -> {Listable},
"RuntimeOptions" -> "Speed"
];
(*F'x answer*)
MakeInPeriodicCellFx =
Compile[{{x, _Real}, {cellwidth, _Real}},
If[x < -(cellwidth/2.), x + cellwidth,
If[x > cellwidth/2., x - cellwidth, x]],
CompilationOptions -> {"ExpressionOptimization" -> True,
"InlineCompiledFunctions" -> True,
"InlineExternalDefinitions" -> True},
RuntimeAttributes -> {Listable},
"RuntimeOptions" -> "Speed"];
data = RandomReal[{-100, 100}, 100000];
(*Original implementation*)
m0 = MakeInPeriodicCellOrig[data, 30]; // AbsoluteTiming (*0.8370473*)
(*my revritten*)
m1 = MakeInPeriodicCellImp[data, 30]; // AbsoluteTiming (*0.0360021*)
(*F'x answer*)
m2 = MakeInPeriodicCellFx[data, 30]; // AbsoluteTiming (*0.0140008*)
m0 == m1 == m2 (*True*)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment