473,805 Members | 2,016 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

static variables question

Hi

I have a function called from another one, which runs in loop, so that
is it called very often
something like this:

void my_function(int x) {
int temp;
temp = x * some_const;

do_something(te mp);
}

suppose that x is changed really rarely ( lets say a hundreds of
calls)
would that be more efficient ?
void my_function(int x) {
static int temp;
if(temp != x * some_const)
temp = x * some_const;

do_something(te mp);
}

why I'm asking is that I'm not sure, if creating temp variable in
every function call takes more time, then if statment. Anyone can
explain this to me a bit ?

thank's, have a nice day !

J.
Jul 22 '05 #1
7 1427

"Jan Bernatik" <be******@kn.vu tbr.cz> wrote in message
news:24******** *************** ***@posting.goo gle.com...
Hi

I have a function called from another one, which runs in loop, so that
is it called very often
something like this:

void my_function(int x) {
int temp;
temp = x * some_const;

do_something(te mp);
}

suppose that x is changed really rarely ( lets say a hundreds of
calls)
would that be more efficient ?
void my_function(int x) {
static int temp;
if(temp != x * some_const)
temp = x * some_const;

do_something(te mp);
}

why I'm asking is that I'm not sure, if creating temp variable in
every function call takes more time, then if statment. Anyone can
explain this to me a bit ?

thank's, have a nice day !

J.


The second look less efficient, but I don't think it has anything to do with
if statements or variables. In the first example you do a multiplication
each time. In the second example you do one or two multiplications and an
equality test. So the second must be slower than the first because it always
does more work.

john
Jul 22 '05 #2
Jan Bernatik wrote:

Hi

I have a function called from another one, which runs in loop, so that
is it called very often
something like this:

void my_function(int x) {
int temp;
temp = x * some_const;

do_something(te mp);
}

suppose that x is changed really rarely ( lets say a hundreds of
calls)
would that be more efficient ?

void my_function(int x) {
static int temp;
if(temp != x * some_const)
temp = x * some_const;

do_something(te mp);
}

why I'm asking is that I'm not sure, if creating temp variable in
every function call takes more time, then if statment. Anyone can
explain this to me a bit ?


Count the number of multiplications you have to do in your
first version (answer: 1)
Count the number of multiplications you have to do in
your second version (answer: at least 1)

So what have you gained? Nothing at all, since in addition
to the one multipication you also have a comparison.

If you want to do some caching, do it correctly. This
means you need to store the output *and* the input to the
fomula. If the input hasn't changed then the previous
formula output can be used:

void my_function( int x ) {
static int LastX = 0;
static int LastResult = 0;

if( x != LastX ) {
LastX = x;
LastResult = x * some_const;
}

do_something( LastResult );
}

Now you have only a comparison that has to be executed in any case.
If that is faster then a single multiplication: you have to try it.

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 22 '05 #3
> void my_function(int x) {
static int temp;
if(temp != x * some_const)
temp = x * some_const;

do_something(te mp);
}

why I'm asking is that I'm not sure, if creating temp variable in
every function call takes more time, then if statment. Anyone can
explain this to me a bit ?


For that thing to work you must initialize the static and
write the code as suggested by Karl Heinz Buchegger:

void my_function( int x ) {
static int LastX = 0;
static int LastResult = 0;

if( x != LastX ) {
LastX = x;
LastResult = x * some_const;
}

do_something( LastResult );
}

On modern processors, this is probably much slower than
computing the multiplication every time. For each local
static variable declaration, the compiler usually puts a
test to see if it's the first time that the function is
executed (in that particular case, maybe not because the
initialization can be done at compile time). Moreover, if
statements are usually very costly because of code
alignment, pipeline issues and branch prediction in the
processor. So even with three multiplications , I guess that
using static variables is slower. Do some tests and give us
your results (might be very platform and optimization
dependent though, and depends also very much on the
frequency of changes of x).

Benoit
Jul 22 '05 #4
"Jan Bernatik" <be******@kn.vu tbr.cz> wrote in message
void my_function(int x) {
int temp;
temp = x * some_const;
do_something(te mp);
}


The principle of caching means it may be more efficient in the following
context. You need 2 static variables -- one holding the raw data like 'x',
and the other the computation of 'x'.

void my_function(int x) {
static int prevx;
static int temp;
if (x != prevx) {
temp = x*some_const; // if this throws we don't set prevx
prevx = x;
}
do_something(te mp);
}

Anyway, this is a good idiom to keep in mind, though it's usually used in
conjunction with mutable class member variables.

But in your case simply multiplying a x with a constant will surely be
faster than my version above. Multiplication is a very fast operation. My
version above has an implicit if statement to see if the variable is
constructed (though by changing the function static variables prevx and temp
to global variables you'll avoid this problem), and another if to see x !=
prevx, and probably most importantly the limitation that temp and prev won't
be stored in registers.

If the computation is anything more complex than consider the caching idiom.

Also, if the value of 'x' doesn't change much, it might be a good idea to
computer x*constant in the calling functions.
Jul 22 '05 #5
It would be more appropriate to call the function as follows,
that saves a comparison statement. Compiler is smart enough
to keep (x*some_const) in the register, if there is a loop.
void my_function(int x) {
/* int temp; */
/* temp = x * some_const; */

//loop!
do_something(x * some_const);
}

be******@kn.vut br.cz (Jan Bernatik) wrote in message news:<24******* *************** ****@posting.go ogle.com>...
Hi

I have a function called from another one, which runs in loop, so that
is it called very often
something like this:

void my_function(int x) {
int temp;
temp = x * some_const;

do_something(te mp);
}

suppose that x is changed really rarely ( lets say a hundreds of
calls)
would that be more efficient ?
void my_function(int x) {
static int temp;
if(temp != x * some_const)
temp = x * some_const;

do_something(te mp);
}

why I'm asking is that I'm not sure, if creating temp variable in
every function call takes more time, then if statment. Anyone can
explain this to me a bit ?

thank's, have a nice day !

J.

Jul 22 '05 #6
thank you guys for response.

Originally, I thought (wasn't sure) if creating temp variable every
time the function is called will take more cpu time, then declare the
variable static. And other thing is, that in theory the computation
can be a lot more complicated, so then it will be useful to use your
methods (caching both raw and computed data).

Sorry I couldn't respond earlier, I have to use google groups.

J.
Jul 22 '05 #7
Karl Heinz Buchegger wrote:
If you want to do some caching, do it correctly. This
means you need to store the output *and* the input to the
fomula. If the input hasn't changed then the previous
formula output can be used:

void my_function( int x ) {
static int LastX = 0;
static int LastResult = 0;

if( x != LastX ) {
LastX = x;
LastResult = x * some_const;
}

do_something( LastResult );
}

Now you have only a comparison that has to be executed in any case.
If that is faster then a single multiplication: you have to try it.


in a project i worked on recently, i had to do a large set of complex
calculations. a very large set. on an even larger set of input data.

one notable thing, though, is that the input data had a lot of duplicate
data points (geographically ). it was pre-sorted, and these duplicate
points often only differed in two values.

i took advantage of that fact to cut the work time in half while
producing accurate (and importantly, identical!) results compared to the
previous data. i only needed to cache a state of some of the processed
data and apply the new values.

it's amazing what one comparison operation can save. :)

(as a side note: the original computation work took an average of 23
hours for 65,000 data points. each point took 400ms to complete. after
using the above method, it was cut down to about 37,000 data
compilations with the simpler math work done for every point. but
still, 11 hours was too long.)

--
-- Charles Banas
Jul 22 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
3676
by: James | last post by:
Hello Java NG, I not sure if this is the right NG for this type of question but if not please let me know which is, TIA Any way first off let me say I'm a student and this WAS last weeks lab, turned in, graded and passed so I'm not trying to get someone to do my lab assignments, but after I got this back I was reading about the DecimalFormat and I tried to format my output but I keep getting an error message. can anyone please tell me...
115
7664
by: Mark Shelor | last post by:
I've encountered a troublesome inconsistency in the C-language Perl extension I've written for CPAN (Digest::SHA). The problem involves the use of a static array within a performance-critical transform function. When compiling under gcc on my big-endian PowerPC (Mac OS X), declaring this array as "static" DECREASES the transform throughput by around 5%. However, declaring it as "static" on gcc/Linux/Intel INCREASES the throughput by...
9
2831
by: AnandRaj | last post by:
Hi guys, I have a few doubts in C. 1. Why static declartions are not allowed inside structs? eg struct a { static int i; }; Throws an error ..
9
2311
by: Neil Kiser | last post by:
I'm trying to understand what defining a class as 'static' does for me. Here's an example, because maybe I am thinking about this all wrong: My app will allows the user to control the fonts that the app uses. So I will need to change the fonts depending on what settings the user has entered. However, it seems kind of wasteful to me to go to teh registry, fetch the font information and create new font objects for every form that I am...
25
5185
by: Sahil Malik [MVP] | last post by:
So here's a rather simple question. Say in an ASP.NET application, I wish to share common constants as static variables in global.asax (I know there's web.config bla bla .. but lets just say I wanna use global.asax) --- Would you declare your static var as --- public static int x ;
28
4650
by: Dennis | last post by:
I have a function which is called from a loop many times. In that function, I use three variables as counters and for other purposes. I can either use DIM for declaring the variables or Static. Would the performance be better using Static versus Dynamic. I would think it would be quicker with STATIC declarations since the variables would only have to be created once. Can anyone confirm this. Thanks. -- Dennis in Houston
9
2183
by: Pohihihi | last post by:
What could be the possible reasons (technical/non technical) of not using lots of static functions or variables in a program keeping in mind that Framework by itself has tons of static functions and variables?
55
6274
by: Zytan | last post by:
I see that static is more restricted in C# than in C++. It appears usable only on classes and methods, and data members, but cannot be created within a method itself. Surely this is possible in C# in some way? Or maybe no, because it is similar to a global variable (with its scope restricted) which C# is dead against? Zytan
37
5489
by: minkoo.seo | last post by:
Hi. I've got a question on the differences and how to define static and class variables. AFAIK, class methods are the ones which receives the class itself as an argument, while static methods are the one which runs statically with the defining class. Hence, my understanding is that static variables must be bound to the class defining the variables and shared by children of parent class where the variable is defined. But, please have a...
0
4070
by: Luis Zarrabeitia | last post by:
Quoting Joe Strout <joe@strout.net>: I'm sure your credentials are bigger than mine. But he is right. A lot of languages have ditched the "concept" of a static variable on a method (how do you parse that sentence, btw?) in favour of using encapsulation. Of the top of my head, there is Java, C# and Python, and I think even PHP and Perl. They call them "private variables", including the name-mangled-publicly-accessible-__python's...
0
9716
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9596
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10607
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10104
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7645
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6875
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4317
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3843
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3007
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.