Is variable++ faster than ++variable?

TimingsOne of the things I as told when I learnt C++ and then later C was that a post-inc (i.e. variable++) was faster than a pre-inc i.e. ++variable. Frankly I’m not sure if it is really true but its not a difficult thing to test.

Here’s a short program

#include <stdio.h>
#include "hr_time.h"

#define NUMLOOPS 100000000

int main() {
  stopWatch s;
  startTimer(&s);
  int j=0;
  for (int i=0;i<NUMLOOPS;i++){
    ++j;
  }
  stopTimer(&s);
  printf("PreInc = %10.5f\n",diff(&s));

  startTimer(&s);   
  j=0;
  for (int i=0;i<NUMLOOPS;i++){
    j--;
  }
  stopTimer(&s);
  printf("PostInc = %10.5f\n",diff(&s));  
}

You can get the siurce code including hr_time.h and .c from the timings.zip file on GitHub. I used VS Code with clang to build this on Ubuntu. Here is the tasks.json file to build it. It assumes that the file is in your workspace folder and creates a file called ex1. The timings.zip file contains the json files as well.

{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "shell",
            "label": "clang build active file",
            "command": "/usr/bin/clang",
            "args": [
                "-g",
                "${file}","${workspaceFolder}/hr_time.c",              
                "-o",
                "${fileDirname}/ex1",                
                "-lm"
            ],
            "options": {
                "cwd": "/usr/bin"
            },
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

Ignore the first three runs which were for 10 million not 100 million. All do indeed show that post-inc is indeed faster. Not by a great margin but each of the last 100 million loops takes between 94% and 96% of the preinc time.

(Visited 85 times, 1 visits today)