c語言函式引數太多對效能是否有影響?

2021-08-19 02:56:56 字數 2606 閱讀 9760

64位彙編(linux)

當引數少於7個時, 引數從左到右放入暫存器: rdi, rsi, rdx, rcx, r8, r9。

當引數為7個以上時, 前 6 個與前面一樣, 但後面的依次從 「右向左」 放入棧中,即和32位彙編一樣。

引數個數大於 7 個的時候

h(a, b, c, d, e, f, g, h);

a->%rdi, b->%rsi, c->%rdx, d->%rcx, e->%r8, f->%r9

h->8(%esp)

g->(%esp)

call h

#include#include#includetypedef struct fun_p_funp;

int func(int aa, int bb, int cc, int dd, char c, int a, int b, int d, double f)

int funcs(int aa, int bb, int cc, int dd, _funp * inp)

int funcs2(int aa, int bb, int cc, int dd, _funp * inp)

int main(void)

, time_end = ;

int aa = 9;

int bb = 12;

int cc = 39;

int dd = 90;

char c = 20;

int a = 98;

int b = 199;

int d = 23;

double f = 34.2;

struct fun_p funp;

int i, j;

int run_num = 1000;

long long total = 0;

funp.c = c;

funp.a = a;

funp.b = b;

funp.d = d;

funp.f = f;

clock_gettime(clock_realtime, &time_start);

for (i = 0; i < run_num; i++)

for (j = 0; j < run_num; j++)

clock_gettime(clock_realtime, &time_end);

printf("func duration:%llus %lluns. total = %lld\n", time_end.tv_sec-time_start.tv_sec, time_end.tv_nsec-time_start.tv_nsec, total);

total = 0;

c = 20;

clock_gettime(clock_realtime, &time_start);

for (i = 0; i < run_num; i++)

for (j = 0; j < run_num; j++)

clock_gettime(clock_realtime, &time_end);

printf("funcs duration:%llus %lluns. total = %lld\n", time_end.tv_sec-time_start.tv_sec, time_end.tv_nsec-time_start.tv_nsec, total);

total = 0;

funp.c = 20;

clock_gettime(clock_realtime, &time_start);

for (i = 0; i < run_num; i++)

for (j = 0; j < run_num; j++)

clock_gettime(clock_realtime, &time_end);

printf("funcs2 duration:%llus %lluns. total = %lld\n", time_end.tv_sec-time_start.tv_sec, time_end.tv_nsec-time_start.tv_nsec, total);

return 1;

}

編譯命令: gcc -o3 test_func_parameter.c -o test_func_parameter -lrt

測試結果表明:

func duration:0s 1633997ns. total = 3235271710

funcs duration:0s 1524616ns. total = 3235271710

funcs2 duration:0s

1023802ns. total = 3235271710

1、func相比funcs消耗的時間差不多,說明如果在函式內部用臨時變數來轉存一遍結構體變數的話,則函式引數多少對效能影響不大。

2、funcs2比funcs少了引數拷貝到函式變數的過程,但是卻可以節省很多時間。說明將部分引數用結構體一次傳輸,並且函式內部通過結構體訪問的話,可以節省時間,因為減少了函式引數過多導致的記憶體寫入操作(引數壓棧)。

3、如果函式本身計算量比較大,那可能引數的傳輸方式對效能影響就比較小了。

為什麼不建議函式有太多引數?

記錄一篇今天工作的思考。為什麼不建議函式的有太多引數?今天做組內 評審時,發現同事的 有乙個小問題,乙個函式新增了乙個引數後有了7個引數,而公司的編碼規範要求,函式的引數不許超過6個。後來我就研究了一下,為啥不建議函式有太多引數呢?當然函式引數太多,不利於維護,學習成本比較高。除此之外,函式引數太多...

c語言 函式引數

引數的使用,在函式中使用了多種引數形式 例 void show n char char ch int num 這行 是通知編譯器show n char 使用名為 ch 和 num 的兩個引數 並且這兩個引數的型別分別是char 和 int 變數 ch 和 num 被稱為形式參量或形式參量 形式參量是...

C語言函式作為函式引數

為了滿足dry思想,減少 的重複性,考慮將函式作為引數傳入另一函式中。c語言是可以將函式作為函式引數的。用到的方法是函式指標。首先需要明確的是,在c語言中,函式名就是函式的首位址,所以將函式作為函式引數的思路是將函式位址傳入,形參是乙個指標型別的變數,形參的基型別為函式原型。引數原型為 elemty...