Re: Increase in efficiency with Module
- To: mathgroup at smc.vnet.net
- Subject: [mg40061] Re: [mg40050] Increase in efficiency with Module
- From: Dr Bob <drbob at bigfoot.com>
- Date: Tue, 18 Mar 2003 02:21:30 -0500 (EST)
- References: <200303170835.DAA22905@smc.vnet.net>
- Reply-to: drbob at bigfoot.com
- Sender: owner-wri-mathgroup at wolfram.com
I don't know the implementation details, but without Module, the function
has side-effects. It changes the values of global symbols (a functional
programming no-no). With Module, the C compiler is free to keep those
values in counter registers, or wherever.
Here's a code that's 20 to 35 percent faster:
ftauc3 = Compile[{{ry, _Real, 1}}, Block[{i = 0, j, a = 0, n = Length@ry},
Do[i++; j = i + 1;
Do[a += Sign[ry[[j]] - ry[[i]]]; j++, {n - i}],
{n - 1}]; a]];
test = Array[Random[Real, 100] &, 500];
Timing@ftauc3[test]
Timing@ftauc2[test, Length@test]
Timing@ftauc[test, Length@test]
{0.06300000000000239*Second, 623}
{4.922000000000004*Second, 623}
{0.0940000000000012*Second, 623}
test = Array[Random[Real, 100] &, 1000];
Timing@ftauc3[test]
Timing@ftauc2[test, Length@test]
Timing@ftauc[test, Length@test]
{0.26499999999998636*Second, 1270}
{20.062999999999988*Second, 1270}
{0.34300000000001774*Second, 1270}
test = Array[Random[Real, 100] &, 5000];
Timing@ftauc3[test]
Timing@ftauc[test, Length@test]
{6.4839999999999804*Second, -128684}
{8.530999999999977*Second, -128684}
Bobby
On Mon, 17 Mar 2003 03:35:18 -0500 (EST), Aaron E. Hirsh
<aehirsh at stanford.edu> wrote:
> I would be grateful if someone could explain the difference in efficiency
> between the following two simple programs. ry is a list of length n. For
> n = 1000, the program using Module takes 1 second on my laptop, whereas
> the program without Module takes 75 seconds.
>
> ftauc = Compile[{{ry, _Real, 1}, {n, _Real, 0}},
> Module[{i, j, a},
> i = 1;
> a = 0;
> Do[
>
> j = i + 1;
> Do[
> If[ry[[i]] < ry[[j]], a++, If[ry[[i]] > ry[[j]], a--]];
> j++, {n - i}];
>
> i++, {n - 1}]; a
> ]]
>
> ftauc2 = Compile[{{ry, _Real, 1}, {n, _Real, 0}},
>
>
>
> i = 1;
> a = 0;
> Do[
> j = i + 1;
>
> Do[
> If[ry[[i]] < ry[[j]], a++, If[ry[[i]] > ry[[j]], a--]];
> j++, {n - i}];
> i++, {n - 1}]; a
> ]
>
> thank you,
--
majort at cox-internet.com
Bobby R. Treat
- References:
- Increase in efficiency with Module
- From: "Aaron E. Hirsh" <aehirsh@stanford.edu>
- Increase in efficiency with Module