Home > other >  Why applying a const attribute to a pure function cannot reduce elapsed time?
Why applying a const attribute to a pure function cannot reduce elapsed time?

Time:02-23

According to the GNU document:

int square (int) __attribute__ ((const)) tells GCC that subsequent calls to function square with the same argument value can be replaced by the result of the first call regardless of the statements in between.

I expect the following code will be slow down when removing __attribute__((const)) in the function declaration.

#include <stdio.h>
#include <limits.h>

int my_double(int b) __attribute__((const));

//int my_double(int b);


int main(void) {

  long result = 0;

  for (int i = 0; i < INT_MAX/2; i  )
  {
     result  = my_double(5);
  }

  printf("%ld\n", result);
}

int my_double(int b) {
  return b*2;
}

However, the experiments show that __attribute__((const)) does not affect timing results significantly. Does anyone know the reason? Thanks.

By the way, I use the following commands to clear any cache that might pollute the timing results of each experiment.

  sudo sh -c 'echo 3 > /proc/sys/vm/drop_caches'
  sudo swapoff -a
  sudo swapon -a

And use /usr/bin/time to time the experiments.

PS. The corresponding assembly is as follows: (I am unfamiliar with assembly)

    .file   "attribute-o.c"
    .text
    .section    .rodata
.LC0:
    .string "%ld\n"
    .text
    .globl  main
    .type   main, @function
main:
.LFB0:
    .cfi_startproc
    endbr64
    pushq   %rbp
    .cfi_def_cfa_offset 16
    .cfi_offset 6, -16
    movq    %rsp, %rbp
    .cfi_def_cfa_register 6
    subq    $16, %rsp
    movq    $0, -8(%rbp)
    movl    $0, -12(%rbp)
    jmp .L2
.L3:
    movl    $5,            
  • Related