A
A
Algoritmus-net2018-09-30 10:50:53
C++ / C#
Algoritmus-net, 2018-09-30 10:50:53

How to speed up the execution of the function call by pointer?

If you add two numbers a billion times in a loop, it will take 2555 ms. If in a loop to call a function a billion times by pointer in which the same two numbers are added, it will take 28345 ms. Why such a time difference, more than 10 times. Variables are not passed to the procedure.

#include <stdio.h>
#include "stdafx.h"
#include <ctime> 
#include <conio.h>
int z = 1;
void add()
{
  z = 1 + 1;
}

int main(void)
{
  void(*operations[1])() = { add };
  
  unsigned int start_time = clock();	
  for (int i = 0; i<1000000000; i++)
  {
    operations[0]();    // вызов функции по указателю
  }
  unsigned int end_time = clock(); 
  unsigned int search_time = end_time - start_time;  // 28345 мс больше в 10 раз
  printf("ykazatel  %d ", search_time);	
  
  //////	
  start_time = clock();
  for (int i = 0; i<1000000000; i++)
  {
    z = 1 + 1;
  }
  end_time = clock(); 
  search_time = end_time - start_time; //  2555 мс
  printf("time  %d ", search_time); 
  ///////	
  
  _getch();
  return 0;
}

In Delphi, if the numbers are added in a loop, 2516 ms, if the procedure using the pointer is 2656 ms, the difference is small, only about 100 ms.
type
 TMyF = procedure;
var
  a: array [1..2] of TMyF;
var
  Form1: TForm1;
   x,i: integer;
  tf,ts,n:integer;
   procedure f2;
implementation

{$R *.dfm}

procedure f2;
begin
 x:=1+1;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
 a[2]:=f2;
 x:=1;

 ts := GetTickCount();
for I := 0 to 1000000000  do
begin
 a[2];
end;
tf := GetTickCount();
mmo1.text:=IntToStr(tf-ts); // 2516 мс

ts := GetTickCount();
for I := 0 to 1000000000  do
begin
 x:=1+1;
end;
tf := GetTickCount();

mmo1.text:=mmo1.text+#13#10+IntToStr(tf-ts); // 2656 мс
 end;
end.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
1
15432, 2018-09-30
@15432

Calling a function is always expensive. With each call, memory is allocated on the stack, jump, return from the function. These actions slow down the execution of the program. The Delphi compiler seems to have removed the jump and inserted the action itself directly into the loop. If you attach the compiled binaries, I will show in an assembler listing what the difference is and why it is slow.

V
Vitaly, 2018-09-30
@vt4a2h

I advise you to build the application in release mode (with all the necessary optimizations) and then profile it. Profiling not in release mode is not indicative.
Well, in general, you were correctly answered that a function call involves a lot of expenses. Another thing is that compilers are very smart and can optimize a lot of things. Of course, not all.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question