Statalist The Stata Listserver

[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

st: Weird problem with nested functions in Mata

From   "Ben Jann" <[email protected]>
To   <[email protected]>
Subject   st: Weird problem with nested functions in Mata
Date   Wed, 12 Apr 2006 16:40:34 +0200

I observed a very strange problem in Mata. Nesting functions 
can have weird effects on execution times although only 
objects' addresses are passed from function to function. Here 
is an example:

	. mata:
	: real colvector test1(x) return(x:*x:*x:*x:*x)
	: real colvector test2(x) return(test1(x))
	: real colvector test3(x) return(test2(x))
	: real colvector test4(x) return(test3(x))
	: real colvector test5(x) return(test4(x))
	: real colvector test6(x) return(test5(x))
	: end
	r; t=0.02 16:22:27
	. mata: x = uniform(1000000,1)
	r; t=0.04 16:22:27
	. mata: z = x:*x:*x:*x:*x
	r; t=0.24 16:22:27
	. mata: z = test1(x)
	r; t=0.38 16:22:28
	. mata: z = test2(x)
	r; t=0.23 16:22:28
	. mata: z = test3(x)
	r; t=0.39 16:22:28
	. mata: z = test4(x)
	r; t=0.23 16:22:28
	. mata: z = test5(x)
	r; t=0.40 16:22:29
	. mata: z = test6(x)
	r; t=0.23 16:22:2

Executing operation "x:*x:*x:*x:*x" directly is fast (t=0.24). 
However, executing the same operation within a function is 
slow (t=0.38). Why is this? It comes worse: Executing the 
operation within a function that is nested within another 
function is fast again! However, adding another level of 
nesting makes the operation slow again, and so on: fast - 
slow - fast - slow ... This really puzzles me. What would be 
the logic behind this? Does anyone have an explanation?


*   For searches and help try:

© Copyright 1996–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index