[英]Execution time between functions with & without arguments C/C++
I'd just like to ask what's the difference in execution time when: 我只想问以下情况下执行时间有何不同?
a) We have variables declared in main()
and send them in functions using arguments a)我们在
main()
声明了变量,并使用参数在函数中将其发送
b) We have global variables and access them directly from functions with no arguments b)我们有全局变量,可以直接从不带参数的函数中访问它们
The thing is I started writing few aps and just saw a few discussions about this, but I haven't yet written any application that makes the difference bigger then few ms. 关键是我开始编写一些Aps,并且看到了一些有关此的讨论,但是我还没有编写任何使两者之间的差异大几毫秒的应用程序。
Passing parameters to function involves usually one of two assembler instructions: push param
(and later pop param
) or mov ax, param
. 将参数传递给函数通常涉及以下两个汇编程序指令之一:
push param
(和后来的pop param
)或mov ax, param
。 Since processor is able to do (a lot) more in a second, such "optimization" mostly probably will go unnoticed (a few ms on the whole program is below the error margin) 由于处理器能够在一秒钟内完成更多(很多)操作,因此这种“优化”很可能不会被注意到(整个程序的几毫秒低于错误余量)
Using global variables in the place of function parameters will cause a huge mess in the code with almost unnoticeable or possibly no performance gain. 使用全局变量代替函数参数会导致代码混乱,几乎不会引起注意,甚至可能不会提高性能。
All of this depends on what CPU and compiler that are used. 所有这些取决于所使用的CPU和编译器。
When you pass a parameter to a function, one of the following could happen: 当您将参数传递给函数时,可能会发生以下情况之一:
Using a global variable is will be ever so slightly faster than using the stack. 使用全局变量将比使用堆栈快得多。 It will unlikley be faster than using a CPU register: inside the function the value might need to be loaded into such a register before calculations anyhow.
它绝对比使用CPU寄存器快:在函数内部,无论如何计算,可能需要将该值加载到此类寄存器中。
It should be noted we are talking about a few CPU ticks here and there. 应该注意的是,我们在这里和那里谈论的是几个CPU滴答声。
My advise: 我的建议:
Stack operations are very efficient, and they are made even more efficient because the stack is likely to be in cache memory. 堆栈操作非常高效,由于堆栈可能位于高速缓存中,因此它们的工作效率更高。 That could make using the stack even faster than not using it.
这可能会使使用堆栈比不使用堆栈更快。
Expect parameter passed variables to be a lot faster than global variables. 期望参数传递的变量比全局变量快很多。 In Modern ABIs, function parameters are passed mostly using CPU registers which are immediately available to the CPU.
在现代ABI中,大多数使用CPU寄存器传递功能参数,而CPU寄存器可立即使用。
Global variables must be read from (static) memory. 全局变量必须从(静态)内存中读取。 Worse than that, static memory is allocated on its own memory page, which is generally far from your stack (or heap) memory.
更糟糕的是,静态内存是在其自己的内存页面上分配的,该页面通常离您的堆栈(或堆)内存很远。 This means that cache misses are more likely which in turn means that access can consume a large number of CPU cycles.
这意味着高速缓存未命中的可能性更高,这又意味着访问可能消耗大量CPU周期。
Obviously this depends a lot on your usage patterns. 显然,这很大程度上取决于您的使用模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.