Re: Replace, ReplaceAll and If time performace comparition
- To: mathgroup at smc.vnet.net
- Subject: [mg127289] Re: Replace, ReplaceAll and If time performace comparition
- From: Dana DeLouis <dana01 at me.com>
- Date: Sat, 14 Jul 2012 01:29:48 -0400 (EDT)
- Delivered-to: l-mathgroup@mail-archive0.wolfram.com
- Delivered-to: mathgroup-newout@smc.vnet.net
- Delivered-to: mathgroup-newsend@smc.vnet.net
> (If[# < 0, 0, #] & /@ randomList); // AbsoluteTiming > {0.572200, Null} > ... There is some trick to make it faster? Hi. You've got a great solution with Clip, but just to add 2 cents.. In other programming languages, sometimes using Max or Min instead of an IF statement is nice. randomList=RandomInteger[{-100,100},10 10^6]; t1=(If[#<0,0,#]&/@randomList);//AbsoluteTiming {0.729998,Null} t2=(Max[#,0]&/@randomList);//AbsoluteTiming {0.454711,Null} t1==t2 True In the old days before Clip, one way was to use two IF statements. One neat technique was to replace the two IF statements with Median. v=RandomInteger[{-100,100},20]; // New Clip[v,{0,1}] {0,0,1,1,1,1,0,1,0,1,0,1,0,0,1,1,1,0,0,0} // Old days Median[{0,#,1}]& /@v {0,0,1,1,1,1,0,1,0,1,0,1,0,0,1,1,1,0,0,0} %%==% True If one were stuck without access to a Median function, then one way without IF statements... Min[Max[0,#],1]& /@ v {0,0,1,1,1,1,0,1,0,1,0,1,0,0,1,1,1,0,0,0} = = = = = = = = = = Dana DeLouis Mac & Math 8 = = = = = = = = = = On Jun 24, 4:24 am, Murta <rodrigomur... at gmail.com> wrote: > HI all > I was working in some simulations with random numbers and get this example of performance comparition. > > randomList = RandomInteger[{-100, 100}, 10 10^6]; > > (randomList /. (x_ /; x < 0 -> 0)); // AbsoluteTiming > {5.747133, Null} > > Replace[randomList, (x_ /; x < 0 -> 0), 1]; // AbsoluteTiming > {4.758984, Null} > > (If[# < 0, 0, #] & /@ randomList); // AbsoluteTiming > {0.572200, Null} > > I personally prefer work with patterns because they are more compact and functional. > Someone knows why patter is one magnitude order slow?? There is some trick to make it faster? > > tks > Murta