CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 13 of 13
  1. #1
    Join Date
    Aug 2006
    Posts
    140

    How to Elegantly code an if()?

    How long does an if condition check take when the result is negative and the if won't need to run?

    I have an app that except for the first time it unnecessarily runs the "if" conditional check like several dozens of million times a day! Is there anyway to just run it once since after the first check it's state doesn't change anymore???

    In my Matlab coding, I'd handle such issues by having the first script do all the checking and set the one time variables and then call script 2 which would then call script 3 to script n accordingly but never returned to script 1 which was a single use script.
    How can one do the same in C# and how do you handle the one time issues and avoid putting them in your code snippet that needs to run say 50 million time / 24 hours?

    thanks
    Last edited by Cy_; January 6th, 2009 at 12:22 PM.

  2. #2
    Join Date
    Mar 2002
    Location
    St. Petersburg, Florida, USA
    Posts
    12,125

    Re: How to Elegantly code an if()?

    The answer (as with ANY performance issue)is to MEASURE the actual time). There are MANY different things which can influence the time, and ANY general answer will have exceptions that will potentially make it wrong for your specific circumstance.
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009,2010
    In theory, there is no difference between theory and practice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

  3. #3
    Join Date
    Aug 2006
    Posts
    140

    Re: How to Elegantly code an if()?

    Quote Originally Posted by TheCPUWizard View Post
    The answer (as with ANY performance issue)is to MEASURE the actual time). There are MANY different things which can influence the time, and ANY general answer will have exceptions that will potentially make it wrong for your specific circumstance.
    I measured it with Matlab which must be slower than C# and a simple if statement with negative result comes to 0.000856 seconds after the first several runs to take advantage of the cach! This is a lot and for just 1 M run takes up 850 seconds of CPU time during an 8 hour period!

    But regardless of how long does it take, what is the best coding approach around this in C#?
    The support people for the said app. comment as follows (do you agree or do you believe there is a more elegant way of coding that would run the if just once?):
    :...There is nowhere else to put said logic. Initialize() should never contain any logic."

  4. #4
    Join Date
    May 2007
    Posts
    1,546

    Re: How to Elegantly code an if()?

    Quote Originally Posted by Cy_ View Post
    How long does an if condition check take when the result is negative and the if won't need to run?
    Anywhere from a few CPU cycles to a few years 100 million executions of the statement is only 1157 executions a second, which (assuming it's a relatively normal if statement) should take a fraction of a microsecond.

    Of course, if the test only needs to be executed once, why not execute the check and then store the result in a boolean in your class? Then you can just do:

    Code:
    public class C
    {
        readonly bool checkPassed;
    
        public C ()
        {
            if (StandardIfStatement == ExpectedResult) 
                checkPassed = true;
    
            // or just do: checkPassed = StandardIfStatement == ExpectedResult;
        }
        public Method ()
        {
            if (checkPassed)
                DoStuff ();
    
            DoOtherStuff ();
        }
    }
    I'd recommend doing this, not for performance reasons, but it makes it clear that the test is only being performed once and will never change. It makes the intent of your code more obvious.

    I measured it with Matlab which must be slower than C# and a simple if statement with negative result comes to 0.000856 seconds after the first several runs to take advantage of the cach! This is a lot and for just 1 M run takes up 850 seconds of CPU time during an 8 hour period!
    Remember that matlab is interpreted and thus is *very* slow as compared to a compiled/jitted language. The results are nowhere near comparable. Run the test in C# and see for yourself.
    www.monotorrent.com For all your .NET bittorrent needs

    NOTE: My code snippets are just snippets. They demonstrate an idea which can be adapted by you to solve your problem. They are not 100% complete and fully functional solutions equipped with error handling.

  5. #5
    Join Date
    Aug 2006
    Posts
    140

    Re: How to Elegantly code an if()?

    Mutant...,
    Thanks for your helpful response, so we're talking like a few nanoseconds here for a simple if statement, I will go working on your suggested approach and probably being a newB will come back with more questions...
    Last edited by Cy_; January 6th, 2009 at 01:45 PM.

  6. #6
    Join Date
    Aug 2006
    Posts
    140

    Re: How to Elegantly code an if()?

    This is the actual code in question, it actually works with the stock market data feed and the "CurrentBar" will only be 0 on the very first tick of the day. The stock will continue to have like 1 million more ticks for the rest of the day and then the same scenario if one is following say 100 different stocks during the day!

    Code:
            /// <summary>
            /// Called on each bar update event (incoming tick)
            /// </summary>
            protected override void OnBarUpdate()
            {
    			if (CurrentBar == 0)
    			{
    				// Initiate our Timer object with an interval of 1000ms (1 second)
    				myTimer.Tick += new EventHandler(TimerEventProcessor);
    				myTimer.Interval = 1000;
    				myTimer.Start();
    			}
            }

  7. #7
    Join Date
    Mar 2002
    Location
    St. Petersburg, Florida, USA
    Posts
    12,125

    Re: How to Elegantly code an if()?

    Quote Originally Posted by Cy_ View Post
    The stock will continue to have like 1 million more ticks for the rest of the day.
    That amounts to over 2000 ticks per minute per stock, and over 3400 ticks per second for the 100 stocks. This means that you need something that can comfortable process each tick in 288 micro-seconds.

    I do not see a means of supporting this data rate (which feed are you using? - none of the ones I am familiar come close toeven 5&#37; of this rate!!!) using conventional desktop or even low end server hardware.

    This will have to be either divided up amongst servers, or you will have to use a high-end heavy-SMP type server.
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009,2010
    In theory, there is no difference between theory and practice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

  8. #8
    Join Date
    Jun 2008
    Posts
    2,477

    Re: How to Elegantly code an if()?

    Could.t you simply create a delegate to handle the instantiation of the timer when the bar has a value of 0?

  9. #9
    Join Date
    May 2007
    Posts
    1,546

    Re: How to Elegantly code an if()?

    You can probably do 100,000,000 integer comparisons in a few seconds. It's a micro-optimisation that'd be much better if it were ignored The rest of the processing will take considerably more CPU time.
    www.monotorrent.com For all your .NET bittorrent needs

    NOTE: My code snippets are just snippets. They demonstrate an idea which can be adapted by you to solve your problem. They are not 100% complete and fully functional solutions equipped with error handling.

  10. #10
    Join Date
    Mar 2007
    Posts
    274

    Re: How to Elegantly code an if()?

    I dont know if delegates can do this in c#. Pretty sure you can in c++ using function pointers. The concept is basically this (NOT ACTUAL CODE):

    Code:
     
    class myClass
    {
        private PointerType goHere = AddressOf(Sub1)
        private void Main()
        { 
            goHere
        }
     
        private void Sub1()
        {
            if ( your condition )
            {
                goHere = AddressOf(Sub2)
            }
        }
     
        private void Sub2()
        {
        }
    }

  11. #11
    Join Date
    Jun 2008
    Posts
    2,477

    Re: How to Elegantly code an if()?

    It would be:

    Code:
    private void Main()
    {
         Bar bar = new Bar();
         bar.ValueIsZero += new EventHandler(bar_ValueIsZero);
         bar.Value = 0;
    }
    
    private void bar_ValueIsZero(object sender, EventArgs e)
    {
         // create new timer here
    }
    Now you do not need an if because you don't have to worry about creating new Timer objects, it will happen automatically when the value of the bar is 0.

  12. #12
    Join Date
    May 2007
    Posts
    1,546

    Re: How to Elegantly code an if()?

    But that is extremely complicated. You're adding a lot of complexity for no performance gain. This is why premature optimisation is bad
    www.monotorrent.com For all your .NET bittorrent needs

    NOTE: My code snippets are just snippets. They demonstrate an idea which can be adapted by you to solve your problem. They are not 100% complete and fully functional solutions equipped with error handling.

  13. #13
    Join Date
    Jun 2008
    Posts
    2,477

    Re: How to Elegantly code an if()?

    Quote Originally Posted by Mutant_Fruit View Post
    But that is extremely complicated. You're adding a lot of complexity for no performance gain. This is why premature optimisation is bad
    I agree with that, but in this case I think it is a better approach. I would rather know that something will always be in the correct state instead of using if's to check. As you say though, that if statement is probably not an issue.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured