I am pretty new to programming and using fortran 90 to write a cfd solver that takes a while to run. I am using a module and derived types to store global variables which are used in subroutines in a large do-loop in my main program. I have noticed that if I am referencing one of these global variables and don't need to alter its value, it is slower to use the variable defined in the module than to create a local variable within the subroutine. For instance, I have a type called grd with a real constant A stored in it. Instead of referencing grd%A over and over in a subroutine, it seems to be faster if I create a local A within the subroutine and assign it upfront, A=grd%A, and use A instead. I've run speed tests and for my particular program and defining this local A gives me about a 10% increase in speed, which ends up being pretty significant.
Can anyone explain why this would be the case? Are local variables always faster? Thanks!
Related
I'm trying to understand if my global variable usage which is being done for convenience and ease of assembly generation has a positive side-effect or not (I guess I'm looking to rid myself of the guilt of having these globals).
Program Details:
Broken up into "operations". Each operation reads I/O then does heavy mathematical compute, lots of special casing of code paths via hand-written assembly.
Single-threaded, will never be multi-threaded
One global variable, a fixed-size pre-allocated array (128K)
One global variable, an integer that acts as a pointer
My justification for using global variables here is primarily that I can then just generate call instructions without having to pass parameters, setting up the stack, etc.
The calls will to be functions like this:
DoSomething1()
{
access global1's memory ...
increment global2 ...
reset code;
}
I can ofcourse generate code for parameters, but then I thought maybe the global variables will likely have a perf benefit as well, since the compiler is going to be a constant address for the access. Of course, my global is extremely likely to be in the cache as well.
Am I thinking about this right? Is it possible that using the global the way I describe will make the compiler try to do load/store as opposed to en register them? In fact, can the compiler en register a global variable?
In Fortran 90, does the number of variables defined in a module affect the performance of execution of a subroutine?
Suppose that I have some variables defined in a module, and I am using all of those variables in my subroutine. Now, I add other variables in my module, but do not use or reference them in my subroutine.
Does it have any effect on access speed? It would surely affect the time required for the allocation of all variables at the beginning of execution, but does it have any other effects?
Maybe there could be different consequences with different compilers. In that case, I am using gfortran, and let's keep it strictly to that.
I am using Sublime and Arduino to program a Barometer (MS5611). But what is the best practice to store variables that is only used as temporary storage inside a specific function:
1) Create private variables in my header file for all variables used?
2) Create the variables inside the functions where they are used?
What takes most processing power and memory usage - (1) create them once as private variables and change the content with the functions, or (2) create the variables each time I call a function?
Always declare them inside the function. This improves readability as it shows the intent behind the declaration. Also it lowers the chance for mistakes.
Wherever possible as "const", e.g.
uint16_t sample_it() {
const uint16_t sample = analogRead(...);
const uint16_t result = do_somehting(sample);
return result;
}
Almost for the same reasons but this also gives the compiler more optimization options.
If and how variables are allocated is up to the compiler and its optimizer. Unless you have very tight performance constraints chances are that the compiler will optimize much better than you would. Actually using global variables instead will sometimes slow down your code. Of course you might avoid allocation. However you will pay by additional storage instructions. On the other hand the "allocation" might get optimized away and then your global variables code becomes slower than the local variables code.
depends on your sample rate, meaning how many times calls the function to save the data?
In any case, it is important to also take into account how empty the memory once you've collected and processed the data, in any case if you do not have a lot of variables, but you have to handle more functions that can use it is best to set them globally.
At least, I do so in my projects, and I have never had a problem.
you should avoid using global variables as they are allocated from the available heap RAM and exist (take up space) for the duration of the program (forever in embedded systems) Globals also make for less maintainable and more fragile programs.
If you only need the data inside a function, declare it there. There is almost no penalty (initialization only) and the used space is automatically returned when the function returns as local variables are placed on the stack as are passed parameters.
I've been reading a lot about why global variables are bad and why they should not be used. And yet most of the commonly used programming languages support globals in some way.
So my question is what is the reason global variables are still needed, do they offer some unique and irreplaceable advantage that cannot be implemented alternatively? Are there any benefits to global addressing compared to user specified custom indirection to retrieve an object out of its local scope?
As far as I understand, in modern programming languages, global addressing comes with the same performance penalty as calculating every offset from a memory address, whether it is an offset from the beginning of the "global" user memory or an offset from a this or any other pointer. So in terms of performance, the user can fake globals in the narrow cases they are needed using common pointer indirection without losing performance to real global variables. So what else? Are global variables really needed?
Global variables aren't generally bad because of their performance, they're bad because in significantly sized programs, they make it hard to encapsulate everything - there's information "leakage" which can often make it very difficult to figure out what's going on.
Basically the scope of your variables should be only what's required for your code to both work and be relatively easy to understand, and no more. Having global variables in a program which prints out the twelve-times tables is manageable, having them in a multi-million line accounting program is not so good.
I think this is another subject similar to goto - it's a "religious thing".
There is a lot of ways to "work around" globals, but if you are still accessing the same bit of memory in various places in the code you may have a problem.
Global variables are useful for some things, but should definitely be used "with care" (more so than goto, because the scope of misuse is greater).
There are two things that make global variables a problem:
1. It's hard to understand what is being done to the variable.
2. In a multithreaded environment, if a global is written from one thread and read by any other thread, you need synchronisation of some sort.
But there are times when globals are very useful. Having a config variable that holds all your configuration values that came from the config file of the application, for example. The alternative is to store it in some object that gets passed from one function to another, and it's just extra work that doesn't give any benefit. In particular if the config variables are read-only.
As a whole, however, I would suggest avoiding globals.
Global variables imply global state. This makes it impossible to store overlapping state that is local to a given part or function in your program.
For example, let stay we store the credentials of a given user in global variables which are used throughout our program. It will now be a lot more difficult to upgrade our program to allow multiple users at the same time. Had we just passed a user's state as a parameter, to our functions, we would have had a lot less problems upgrading to multiple users.
my question is what is the reason global variables are still needed,
Sometimes you need to access the same data from a lot of different functions. This is when you need globals.
For instance, I am working on a piece of code right now, that looks like this:
static runtime_thread *t0;
void
queue_thread (runtime_thread *newt)
{
t0 = newt;
do_something_else ();
}
void
kill_and_replace_thread (runtime_thread *newt)
{
t0->status = dead;
t0 = newt;
t0->status = runnable;
do_something_else ();
}
Note: Take the above as some sort of mixed C and pseudocode, to give you an idea of where a global is actually useful.
Static Global is almost mandatory when writing any cross platform library. These Global Variables are static so that they stay within the translation unit. There are few if any cross platform libraries that does not use static global variables because they have to hide their platform specific implementation to the user. These platform specific implementations are held in static global variables. Of course, if they use an opaque pointer and require the platform specific implementation to be held in such a structure, they could make a cross platform library without any static global. However, such an object needs to be passed to all functions within such a library. Therefore, you have a pass this opaque pointer everywhere, or make static global variables.
There's also the identifier limit issue. Compilers (especially older ones) have a limit to the number of identifiers they could handle within a scope. Many operating systems still use tons of #define instead of enumerations because their old compilers cannot handle the enumeration constants that bloat their identifiers. A proper rewrite of the header files could solve some of these.
Global variables are considered when you want to use them in every function including main. Also remember that if you initialize a variable globally, its initial value will be same in every function, however you can reinitialize it inside a function to use a different value for that variable in that function. In this way you don't have to declare the same variable again and again in each function. But yes they can cause trouble at times.
List item
Global names are available everywhere. You may unknowingly end up using a global when you think you are using a local
And if you make a mistake while declaring a global variable, then you'll have to apply the changes to the whole program like if you accidentally declared it to be int instead of float
I have a few global vars I need to set the value to, should I set it into the main/winmain function? or should I set it the first time I use each var?
Instead, how about not using global variables at all?
Pass the variables as function parameters to the functions that need them, or store pointers or references to them as members of classes that use them.
Is there a chance that you won't be using the global var? Is calculating any of them expensive? If so then you have a argument for lazy initialization. If they are quick to calculate or always going to be used then init them on startup. There is no reason not to, and you will save yourself the head ache of having to check for initialization every time you use it.
When the linker links your program together, global variables (also known as writable static data) are assigned to their own section of memory (the ELF .data section) and have a value pre-assigned to them. This will mean that the compiler will not need to generate instructions to initialize them. If you initialize them in the main function, the compiler will generate initialization instructions unless it is clever enough to optimize them out.
This is certainly true for ELF file formats, I am not sure about other executable formats.