Skip to content

Instantly share code, notes, and snippets.

@aaangeletakis
Last active January 19, 2020 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaangeletakis/952389a1740413739ce422112c3b56fa to your computer and use it in GitHub Desktop.
Save aaangeletakis/952389a1740413739ce422112c3b56fa to your computer and use it in GitHub Desktop.

Below is a program to test the speed of certian io functions -- fwrite wins most of the time

#include <iostream>
#include <stdio.h>
#include <chrono>

// Check windows
#if _WIN32 || _WIN64
 #if _WIN64
  #define ENVIRONMENT64
 #else
  #define ENVIRONMENT32
 #endif
#endif

// Check GCC
#if __GNUC__
 #if __x86_64__ || __ppc64__
  #define ENVIRONMENT64
 #else
  #define ENVIRONMENT32
 #endif
#endif

#ifdef ENVIRONMENT64
 #define  int_fast  int_fast64_t
 #define uint_fast uint_fast64_t
#else
 #ifdef ENVIRONMENT32
  #define  int_fast  int_fast32_t
  #define uint_fast uint_fast32_t
 #endif
#endif

#define arrSize(A) (sizeof(A)/sizeof(A[0]))
#define conststr_print(str) fwrite(str, sizeof(char), sizeof(str), stdout)
typedef void (*jumptable)(void);

const char * stdioFunctions [] = {"fwrite", "puts", "printf", "cout"};
uint_fast    times          [] = { 0,        0,      0,        0};

static __inline__ const uint_fast smallest(const uint_fast *__restrict arr, const uint_fast &__restrict size) 
{ 
    int_fast min = arr[0];
    uint_fast s=0;
    for (uint_fast i = 1; i < size; ++i) {
        if (arr[i] < min) {
            min = arr[i];
            s=i;
        }
    }
    return s;
} 

int main(void) {
  constexpr int numberOfTimesToPrintString=10000;
  jumptable jt[] = {
  [](void){
    for(int i=0; i<numberOfTimesToPrintString;++i){(void)conststr_print("Hello World!\n");}
  },
  [](void){
    for(int i=0; i<numberOfTimesToPrintString;++i){(void)puts("Hello World!");}
  },
  [](void){
    for(int i=0; i<numberOfTimesToPrintString;++i){(void)printf("Hello World!\n");}
  },
  [](void){
    for(int i=0; i<numberOfTimesToPrintString;++i){std::cout << "Hello World!\n";}
  }
  };
  constexpr int jtblSize = arrSize(jt);

  std::chrono::time_point<std::chrono::high_resolution_clock> start, stop;

  for(int i=0; i<jtblSize; i++){
    start = std::chrono::high_resolution_clock::now(); 
    jt[i]();
    stop = std::chrono::high_resolution_clock::now();
    times[i]=std::chrono::duration_cast<std::chrono::microseconds>(stop - start).count();
  }

  for(int i=0; i<jtblSize; i++){
    std::cout << stdioFunctions[i] << ": " << times[i] << " microseconds\n";
  }

  std:: cout << "The fastest stdio fuction was '" << 
                stdioFunctions[smallest(times, jtblSize)] << "'\n";
  return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment