Snippets

Willy Pillow iostream vs optimized getInt benchmark

Created by Willy Pillow
// Input is the same as https://bitbucket.org/snippets/WillyPillow/My4qd/cstdio-vs-iostream-benchmark
ubuntu@ubuntu:~$ cat opt.cpp
#include <cstdio>
#include <iostream>

static inline int fast_atoi(const char *p, unsigned int len) {
  int res = 0;
  bool neg = false;
  if (*p == '-') {
    neg = true;
    p++;
    len--;
  }
  switch (len) {
    case 10: res += (*p++ & 15) * 1000000000;
    case 9: res += (*p++ & 15) * 100000000;
    case 8: res += (*p++ & 15) * 10000000;
    case 7: res += (*p++ & 15) * 1000000;
    case 6: res += (*p++ & 15) * 100000;
    case 5: res += (*p++ & 15) * 10000;
    case 4: res += (*p++ & 15) * 1000;
    case 3: res += (*p++ & 15) * 100;
    case 2: res += (*p++ & 15) * 10;
    case 1: res += (*p & 15);
  }
  if (neg) return -res;
  return res;
}

bool getInt(int *res) {
  char numBuf[11], tmp;
  unsigned int i = 0;
  while (true) {
    static char buf[1 << 20], *p = buf, *end = buf;
    if (p == end) {
      if ((end = buf + fread(buf, 1, 1 << 20, stdin)) == buf) break;
      p = buf;
    }
    tmp = *p++;
    if ((unsigned)(tmp - '0') > 10u && tmp != '-') break;
    numBuf[i++] = tmp;
  }
  if (!i) return false;
  *res = fast_atoi(numBuf, i);
  return true;
}

int main() {
  int parity = 0, x;
  while (getInt(&x)) parity ^= x;
  std::cin.tie(0);
  std::ios_base::sync_with_stdio(0);
  std::cout << parity;
  return 0;
}

ubuntu@ubuntu:~$ time ./iostream < input2.txt 
-816737107
real	0m4.424s
user	0m4.360s
sys	0m0.068s

ubuntu@ubuntu:~$ time ./opt < input2.txt
-816737107
real	0m1.072s
user	0m1.000s
sys	0m0.068s

ubuntu@ubuntu:~$ time ./iostream < input2.txt 
-816737107
real	0m4.454s
user	0m4.388s
sys	0m0.064s

ubuntu@ubuntu:~$ time ./opt < input2.txt
-816737107
real	0m1.071s
user	0m0.992s
sys	0m0.076s

ubuntu@ubuntu:~$ time ./iostream < input2.txt 
-816737107
real	0m4.467s
user	0m4.412s
sys	0m0.056s

ubuntu@ubuntu:~$ time ./opt < input2.txt
-816737107
real	0m1.072s
user	0m1.004s
sys	0m0.064s

ubuntu@ubuntu:~$ time ./iostream < input2.txt 
-816737107
real	0m4.422s
user	0m4.368s
sys	0m0.052s

ubuntu@ubuntu:~$ time ./opt < input2.txt
-816737107
real	0m1.071s
user	0m0.996s
sys	0m0.072s

ubuntu@ubuntu:~$ time ./iostream < input2.txt 
-816737107
real	0m4.422s
user	0m4.356s
sys	0m0.064s

ubuntu@ubuntu:~$ time ./opt < input2.txt
-816737107
real	0m1.072s
user	0m1.004s
sys	0m0.068s

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.