c++ How to be efficient with my function use?
I'm running a simulation which takes some time to run and I want to improve that. From what I understood, passing a value to a function means that that value is copied which is slow. Is there a way to include some functions in a dedicated file where I won't need to copy the values?
I don't mind to do "Wrong programing" (global variable, public access etc.) to gain speed.
Thanks
Edit: when I started my project, I tested several loops. I counted processor style between the start and the stop of a loop of that kind:
int i = 0;
while (i < 10000000){
i = doStuff(i); //or doStuf开发者_运维百科f();
}
int doStuff(i){
return i++;
}
int doStuff(){
return i++;
}
I'm pretty sure that the doStuff() case was 10 times faster. I have changed my previous code to global variables and direct access ("wrong programming") and it improved my runtime significantly. I tried to use references but I had some inherent problem which prevented me from doing so (I don't remember what it was). Anyhow, I'm playing around with gprof now.
You could use references. If you have some function:
void Examine(BigHairyObject o) {
cout << o.data[1234]; /* for example */
}
you can avoid a copy by passing a reference to that object:
void Examine(BigHairyObject & o) {
cout << o.data[1234]; /* use is identical */
}
The downside of this, is that you are only referring to the original object, not some copy of it. So, if you modify o
(in this example), you are actually modifying the caller's object.
If you want to promise not to modify the object (and in that case, a reference is usually exactly as good as a copy), use the const
keyword:
void Examine(const BigHairyObject & o) {
cout << o.data[1234]; /* use is identical */
// o.data[1234] = 5; // would cause compile error.
}
The way to approach performance tuning is to let the running program tell you what you should optimize. It's probably different from what you are thinking, and there's probably more than one thing you can fix.
If your guess is correct, that it's got to do with function calls and global variables, I'd be surprised. But, regardless, the program itself can tell you.
Here's an example that demonstrates what I mean. It's a simulation program that gets a very large speedup by fixing things that could not have been guessed.
精彩评论