c++ - Optimised range checking and returning a value -


i have below function returns value based on input. need make code fast possible, without using divison or modulo operator or loops. each consecutive value separated amount equal 6553.

int getscalingfactor(int input) {     unsigned int factor = 0;      if(input < 13107) factor = 72816;     else if(input < 19660) factor = 81918;     else if(input < 26214) factor = 93621;     else if(input < 32767) factor = 109225;     else if(input < 39321) factor = 131070;     else if(input < 45874) factor = 163837;     else if(input < 52428) factor = 218450;     else if(input < 58981) factor = 327675;      return factor; } 

you prepare table containing 72816 repeated 13107 times, 81918 repeated 19660-13107 times, , on, , check upper bound (58981). if within bounds, return table[input] else return 0 (should) do.

no division, no modulo, allocated memory (well below 1 megabyte), , pre-computed table.

proof of concept:

#include <stdio.h> #include <stdint.h>  int32_t table[58981];  void prepare_table() {     int32_t input,factor;     (input=0;input<sizeof(table)/sizeof(table[0]);input++)     {     // reusing code as-is, create table      if(input < 13107) factor = 72816;     else if(input < 19660) factor = 81918;     else if(input < 26214) factor = 93621;     else if(input < 32767) factor = 109225;     else if(input < 39321) factor = 131070;     else if(input < 45874) factor = 163837;     else if(input < 52428) factor = 218450;     else if(input < 58981) factor = 327675;      table[input] = factor;     }  } int getscalingfactor(int input) {     return input < sizeof(table)/sizeof(table[0]) ? table[input] : 0; }  int main() {     prepare_table();     printf("%d => %d\n",19600,getscalingfactor(19600));    printf("%d => %d\n",26200,getscalingfactor(26200));    printf("%d => %d\n",58000,getscalingfactor(58000));    printf("%d => %d\n",60000,getscalingfactor(60000));  } 

so it's memory vs computation tradeoff. if cannot afford cache miss, have no option left other division or multiple tests.


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -