Switch Optimization

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Mike and Jo

    Switch Optimization

    I've been converting some code to C++. I'm trying to use the Switch
    function to compare a result. Is it possible to use switch to evaluate
    '>0', '<0', 0?

    Example

    switch (result)
    {
    case (>0):
    case (<0):
    default:
    }

    I know this can be done in other languages but all the documentation I have
    found in C++ show that you must evaluate const expressions (single values).
    I am currently using and If - Else If - Else structure. Does anyone have an
    efficient work around I can persue?

    Thanx
    Mike


  • Gianni Mariani

    #2
    Re: Switch Optimization

    Mike and Jo wrote:[color=blue]
    > I've been converting some code to C++. I'm trying to use the Switch
    > function to compare a result. Is it possible to use switch to evaluate
    > '>0', '<0', 0?
    >
    > Example
    >
    > switch (result)
    > {
    > case (>0):
    > case (<0):
    > default:
    > }
    >
    > I know this can be done in other languages but all the documentation I have
    > found in C++ show that you must evaluate const expressions (single values).
    > I am currently using and If - Else If - Else structure. Does anyone have an
    > efficient work around I can persue?[/color]

    "if () {} else if () {} else {}" is pretty fast and likely faster than
    or equal to "switch ( result == 0 ? ( result > 0 ? GT : LT ) : EQL )"

    If you know the data you could make it so the first if succeeded most of
    the time but even there, I've just spent more time typing this response
    that you will likely ever save.

    Comment

    • Jack Klein

      #3
      Re: Switch Optimization

      On Wed, 15 Oct 2003 20:20:34 -0400, "Mike and Jo"
      <micheal.c@symp atico.ca> wrote in comp.lang.c++:
      [color=blue]
      > I've been converting some code to C++. I'm trying to use the Switch
      > function to compare a result. Is it possible to use switch to evaluate
      > '>0', '<0', 0?[/color]

      No.
      [color=blue]
      > Example
      >
      > switch (result)
      > {
      > case (>0):
      > case (<0):
      > default:
      > }
      >
      > I know this can be done in other languages but all the documentation I have
      > found in C++ show that you must evaluate const expressions (single values).
      > I am currently using and If - Else If - Else structure. Does anyone have an
      > efficient work around I can persue?
      >
      > Thanx
      > Mike[/color]

      The case labels in a switch statement must be compile-time constant
      expressions that evaluate to an integer type value (meaning any
      integer type, not just int).

      --
      Jack Klein
      Home: http://JK-Technology.Com
      FAQs for
      comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
      comp.lang.c++ http://www.parashift.com/c++-faq-lite/
      alt.comp.lang.l earn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq

      Comment

      • Mike Wahler

        #4
        Re: Switch Optimization

        "Mike and Jo" <micheal.c@symp atico.ca> wrote in message
        news:ivljb.7572 $cT6.377114@new s20.bellglobal. com...[color=blue]
        > I've been converting some code to C++. I'm trying to use the Switch
        > function to compare a result. Is it possible to use switch to evaluate
        > '>0', '<0', 0?[/color]

        No. Also note that switch statements work the same
        in C++ as in C.

        'switch' is intended for use to compare a single
        (variable) value against a set of known values.

        [color=blue]
        > Example
        >
        > switch (result)
        > {
        > case (>0):[/color]
        [color=blue]
        >0 is not a value.[/color]
        result > 0 has a value[color=blue]
        > case (<0):[/color]

        <0 is not a value.
        result < 0 has a value.
        [color=blue]
        > default:
        > }[/color]

        If you insist:

        switch(result) {
        case 0:
        /* result == 0 */
        break;
        default:
        /* result != 0 */
        switch(result > 0) {
        case 1:
        /* result > 0 */
        break;
        default:
        /* result < 0 */
        break;
        }
        }
        /* total of 15 lines */

        But that's just silly. :-)

        if(result)
        ; /* result > 0 or < 0 */
        else
        if(result > 0)
        ; /* result > 0 */
        else
        ; /* result == 0 */

        /* total of 7 lines. */

        Also, the words 'if' and 'else' are shorter to type
        than 'switch', 'case n:', and 'default', don't you think? :-)


        I think you're wanting to use a tool for a task
        for which it is not suited and for which a better one
        already exists.
        [color=blue]
        > I know this can be done in other languages[/color]

        IMO that's no reason to want to do it in C++
        [color=blue]
        >but all the documentation I have
        > found in C++ show that you must evaluate const expressions (single[/color]
        values).

        That's right.
        [color=blue]
        > I am currently using and If - Else If - Else structure. Does anyone have[/color]
        an[color=blue]
        > efficient work around I can persue?[/color]

        What's wrong with if/else?

        -Mike


        Comment

        • David White

          #5
          Re: Switch Optimization

          Mike and Jo <micheal.c@symp atico.ca> wrote in message
          news:ivljb.7572 $cT6.377114@new s20.bellglobal. com...[color=blue]
          > I've been converting some code to C++. I'm trying to use the Switch
          > function to compare a result. Is it possible to use switch to evaluate
          > '>0', '<0', 0?[/color]

          No.
          [color=blue]
          > Example
          >
          > switch (result)
          > {
          > case (>0):
          > case (<0):[/color]

          The cases have to integral constants, not operations.
          [color=blue]
          > default:
          > }
          >
          > I know this can be done in other languages but all the documentation I[/color]
          have[color=blue]
          > found in C++ show that you must evaluate const expressions (single[/color]
          values).[color=blue]
          > I am currently using and If - Else If - Else structure. Does anyone have[/color]
          an[color=blue]
          > efficient work around I can persue?[/color]

          Your question implies that if/else is not efficient, but I don't see what's
          wrong with it or how it could be improved upon.

          DW



          Comment

          • Mike and Jo

            #6
            Re: Switch Optimization


            "Mike Wahler" Replied:

            [snip]
            [color=blue]
            > If you insist:
            >
            > switch(result) {
            > case 0:
            > /* result == 0 */
            > break;
            > default:
            > /* result != 0 */
            > switch(result > 0) {
            > case 1:
            > /* result > 0 */
            > break;
            > default:
            > /* result < 0 */
            > break;
            > }
            > }
            > /* total of 15 lines */[/color]

            Thank you for your suggestion.

            [snip]

            [color=blue][color=green]
            > > I know this can be done in other languages[/color]
            >
            > IMO that's no reason to want to do it in C++[/color]

            I was rather suprised when I translated a VB sort routine I use to C++ and
            found the VB routine ran 3X as fast as the C++ routine. This portion (the
            switch function) allows me to 'break' from the routine which is heavily used
            in an indexing function. When this routine is constantly called hundreds of
            throusands of times when comparing indexed arrays - that minute advantage
            that the 'break' gives me really adds up.

            Maybe the problem lies within the way I am accessing my arrays. I am not
            very knowledgeable in C++.


            Thank you for your response.
            Mike


            Comment

            • David B. Held

              #7
              Re: Switch Optimization

              "Mike and Jo" <micheal.c@symp atico.ca> wrote in message
              news:lomjb.7588 $cT6.385483@new s20.bellglobal. com...[color=blue]
              > [...]
              > I was rather suprised when I translated a VB sort routine I
              > use to C++ and found the VB routine ran 3X as fast as the
              > C++ routine.
              > [...][/color]

              I'm surprised too! If you can, please post both the VB and
              C++ code for the sort routine. There is probably a better
              way to write your C++ version, and you might learn a few
              new tricks in the process.

              Dave



              ---
              Outgoing mail is certified Virus Free.
              Checked by AVG anti-virus system (http://www.grisoft.com).
              Version: 6.0.521 / Virus Database: 319 - Release Date: 9/23/2003


              Comment

              • Peter van Merkerk

                #8
                Re: Switch Optimization

                > I've been converting some code to C++. I'm trying to use the Switch[color=blue]
                > function to compare a result. Is it possible to use switch to[/color]
                evaluate[color=blue]
                > '>0', '<0', 0?
                >
                > Example
                >
                > switch (result)
                > {
                > case (>0):
                > case (<0):
                > default:
                > }
                >
                > I know this can be done in other languages but all the documentation I[/color]
                have[color=blue]
                > found in C++ show that you must evaluate const expressions (single[/color]
                values).[color=blue]
                > I am currently using and If - Else If - Else structure. Does anyone[/color]
                have an[color=blue]
                > efficient work around I can persue?[/color]

                The reason that switch *may* (but not necessarilly does!) produce faster
                code is that it is much more restricted than the if/else if/else
                construct. If C++ would allow you to use switch the way you suggested,
                there is no reason an optimizing compiler would produce faster code with
                a switch statement than with the if/else if/else construct.

                Are you sure that the if/else if/else is really the performance
                bottleneck of your code, and if so how did you come to that conclusion?

                --
                Peter van Merkerk
                peter.van.merke rk(at)dse.nl





                Comment

                • Mike Wahler

                  #9
                  Re: Switch Optimization


                  "David B. Held" <dheld@codelogi cconsulting.com > wrote in message
                  news:bmleq5$rl0 $1@news.astound .net...[color=blue]
                  > "Mike and Jo" <micheal.c@symp atico.ca> wrote in message
                  > news:lomjb.7588 $cT6.385483@new s20.bellglobal. com...[color=green]
                  > > [...]
                  > > I was rather suprised when I translated a VB sort routine I
                  > > use to C++ and found the VB routine ran 3X as fast as the
                  > > C++ routine.
                  > > [...][/color]
                  >
                  > I'm surprised too! If you can, please post both the VB and
                  > C++ code for the sort routine.[/color]

                  Or try std::sort with the C++ code instead of the
                  hand rolled one.

                  -Mike


                  Comment

                  • Karl Heinz Buchegger

                    #10
                    Re: Switch Optimization



                    Mike and Jo wrote:[color=blue]
                    >
                    > I was rather suprised when I translated a VB sort routine I use to C++ and
                    > found the VB routine ran 3X as fast as the C++ routine.[/color]

                    Did you write your own sort function?
                    C++ already has one general purpose sort functionality. For the average
                    programmer it is probably faster then anything they can write on their
                    own.


                    --
                    Karl Heinz Buchegger
                    kbuchegg@gascad .at

                    Comment

                    • lilburne

                      #11
                      Re: Switch Optimization

                      Peter van Merkerk wrote:
                      [color=blue]
                      >
                      > Are you sure that the if/else if/else is really the performance
                      > bottleneck of your code, and if so how did you come to that conclusion?
                      >[/color]

                      I suspect he has no such evidence. The compiler will convert
                      a most switches into an ifelse sequence anyway.

                      Comment

                      • Mike and Jo

                        #12
                        Re: Switch Optimization


                        "lilburne" Wrote:[color=blue]
                        >
                        > I suspect he has no such evidence. The compiler will convert
                        > a most switches into an ifelse sequence anyway.
                        >[/color]

                        I was too quick in assuming the problem lies within the switch function. It
                        was the only difference I initially noticed between the two pieces of code.
                        Since the indexing function I use accesses the switch function 2.3 million
                        times in the process I run I thought that was the problem. As I stated
                        previously my I am not very knowledgable in C++.

                        After the replies I was given I wanted to see the actual gain in using
                        switch in the way I wanted. Being able to leave the comparison function
                        without comparing remaining expressions.

                        I timed a switch function compared with an if/elseif/else function. In C++
                        the if/elseIf/else out performed the the switch by a factor of 1.29 in my
                        particular scenario. (If clause 90 ms / switch clause 116 ms based on 10
                        million iterations in total. Used values 0,1,2 in the order if 0/else if 1/
                        else). This MAY not be the case if you have a large number of expressions
                        to compare in the switch function. I would place the most likely
                        expressions near the begining of the switch function in hope that the break
                        would let me leave the function early and not compare the switch against all
                        other expressions. I did not run timings on this so I do not know for sure
                        (stop assuming things - check).

                        The problem with my code obviously lies elsewhere - but I do know that the
                        if/elseif/else runs faster with my compiler than the switch.

                        Thank you for the responses
                        Mike


                        Comment

                        • Peter van Merkerk

                          #13
                          Re: Switch Optimization

                          > > Are you sure that the if/else if/else is really the performance[color=blue][color=green]
                          > > bottleneck of your code, and if so how did you come to that[/color][/color]
                          conclusion?[color=blue]
                          >
                          > I suspect he has no such evidence. The compiler will convert
                          > a most switches into an ifelse sequence anyway.[/color]

                          I have seen compilers converting long switch/case statements to a jump
                          table indexed by the value of the switch condition. This saves a lot of
                          values comparisions. I can imagine that it would be more difficult (but
                          not impossible) for the compiler to make the same optimization with an
                          if/else if /else sequence.

                          --
                          Peter van Merkerk
                          peter.van.merke rk(at)dse.nl



                          Comment

                          • Peter van Merkerk

                            #14
                            Re: Switch Optimization

                            > > I suspect he has no such evidence. The compiler will convert[color=blue][color=green]
                            > > a most switches into an ifelse sequence anyway.[/color]
                            >
                            > I was too quick in assuming the problem lies within the switch[/color]
                            function. It[color=blue]
                            > was the only difference I initially noticed between the two pieces of[/color]
                            code.[color=blue]
                            > Since the indexing function I use accesses the switch function 2.3[/color]
                            million[color=blue]
                            > times in the process I run I thought that was the problem. As I[/color]
                            stated[color=blue]
                            > previously my I am not very knowledgable in C++.
                            >
                            > After the replies I was given I wanted to see the actual gain in using
                            > switch in the way I wanted. Being able to leave the comparison[/color]
                            function[color=blue]
                            > without comparing remaining expressions.
                            >
                            > I timed a switch function compared with an if/elseif/else function.[/color]
                            In C++[color=blue]
                            > the if/elseIf/else out performed the the switch by a factor of 1.29[/color]
                            in my[color=blue]
                            > particular scenario. (If clause 90 ms / switch clause 116 ms based[/color]
                            on 10[color=blue]
                            > million iterations in total. Used values 0,1,2 in the order if 0/else[/color]
                            if 1/[color=blue]
                            > else). This MAY not be the case if you have a large number of[/color]
                            expressions[color=blue]
                            > to compare in the switch function. I would place the most likely
                            > expressions near the begining of the switch function in hope that the[/color]
                            break[color=blue]
                            > would let me leave the function early and not compare the switch[/color]
                            against all[color=blue]
                            > other expressions. I did not run timings on this so I do not know for[/color]
                            sure[color=blue]
                            > (stop assuming things - check).[/color]

                            Depending on the optimization capabilities of your compiler and the
                            'case' values, reordering cases may or may not help.
                            [color=blue]
                            > The problem with my code obviously lies elsewhere - but I do know that[/color]
                            the[color=blue]
                            > if/elseif/else runs faster with my compiler than the switch.[/color]

                            Try to run your code through a profiler, this should pin-point in which
                            function the most time is spend. You could also post the relevant
                            (compilable) code here if it is not too long. People here may be able to
                            give you advice how to improve the performance of your code.

                            --
                            Peter van Merkerk
                            peter.van.merke rk(at)dse.nl


                            Comment

                            • Thomas Matthews

                              #15
                              Re: Switch Optimization

                              Peter van Merkerk wrote:[color=blue][color=green][color=darkred]
                              >>>Are you sure that the if/else if/else is really the performance
                              >>>bottleneck of your code, and if so how did you come to that[/color][/color]
                              >
                              > conclusion?
                              >[color=green]
                              >>I suspect he has no such evidence. The compiler will convert
                              >>a most switches into an ifelse sequence anyway.[/color]
                              >
                              >
                              > I have seen compilers converting long switch/case statements to a jump
                              > table indexed by the value of the switch condition. This saves a lot of
                              > values comparisions. I can imagine that it would be more difficult (but
                              > not impossible) for the compiler to make the same optimization with an
                              > if/else if /else sequence.
                              >
                              > --
                              > Peter van Merkerk
                              > peter.van.merke rk(at)dse.nl
                              >
                              >
                              >[/color]

                              One could create their own "jump table" by using either a
                              map<key, function pointer> or a table of such records.
                              But this depends on the selection criteria.

                              --
                              Thomas Matthews

                              C++ newsgroup welcome message:

                              C++ Faq: http://www.parashift.com/c++-faq-lite
                              C Faq: http://www.eskimo.com/~scs/c-faq/top.html
                              alt.comp.lang.l earn.c-c++ faq:

                              Other sites:
                              http://www.josuttis.com -- C++ STL Library book

                              Comment

                              Working...