Thread: Which code is better and faster ? Execution time...

  1. #1
    Registered User
    Join Date
    Feb 2012
    Posts
    3

    Which code is better and faster ? Execution time...

    Hello everyone,

    I'm a french student in C#, I'm a beginner in developpement and I try to understand the mechanics of the C#.

    Can you advice to me which code is better and faster to execute and why ? (without tell to me that I've done a function which already exists)

    I tried to calculate execution's time but I fail !

    Sorry for my bad english.



    Code:
    char[] voyelle = { 'a', 'e', 'i', 'o', 'u', 'y' };            
    int[] nbVoyelle = new int[voyelle.Length];
                string mot;
                int j; 
    
    
                Console.WriteLine("Saisir un mot");
                mot = Console.ReadLine();
                DateTime InstantDepart = DateTime.Now;
    
    
              
                for (int i = 0; i < voyelle.Length; i++)
                {                
                    j = 0;
                    while (j != mot.Length - 1)
                    {                    
                        if (voyelle[i] == mot[j])                                            
                            nbVoyelle[i]++;            
                        j++;
                    }
                }
     
                for (int i = 0; i < voyelle.Length; i++)
                    Console.WriteLine("{0} apparait {1} fois.\n", voyelle[i], nbVoyelle[i]);
    
                TimeSpan TempTempsExec = (DateTime.Now - InstantDepart);
                Console.WriteLine("temps execution : {0}\n", TempTempsExec);
                 Console.ReadLine();

    Code:
    char[] voyelle = { 'a', 'e', 'i', 'o', 'u', 'y' };            
    int[] nbVoyelle = new int[voyelle.Length];
                string mot;
                int j; 
    
    
                Console.WriteLine("Saisir un mot");
                mot = Console.ReadLine();
                 
                DateTime InstantDepart = DateTime.Now;
                for (int i = 0; i < voyelle.Length; i++)
                {
                    string copie = mot;
                    j = 0;
                    while (j != copie.Length - 1)
                    {                 
                        
                        j = copie.IndexOf(voyelle[i]);
                        if (j != -1)
                        {
                            copie = copie.Substring(j + 1);
                            nbVoyelle[i]++;
                        }
                        else
                            break;
                     }
                }
    
                for (int i = 0; i < voyelle.Length; i++)
                    Console.WriteLine("{0} apparait {1} fois.\n", voyelle[i], nbVoyelle[i]);
    
                TimeSpan TempTempsExec = (DateTime.Now - InstantDepart);
                Console.WriteLine("temps execution : {0}\n", TempTempsExec);
                Console.ReadLine();

  2. #2
    Registered User vohu's Avatar
    Join Date
    Feb 2012
    Posts
    6

    Thumbs up

    hello,I think that your 2 codes are equals after compilation, but, expect other response

  3. #3
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    Be careful to not fall into the premature optimization trap. The real bottleneck is going to be the user input, and unless they type an extremely large amount of text, the difference between algorithms is going to be inconsequential.

    Also, in order to make your intent clearer, you might want to consider LINQ:
    Code:
            static void Main(string[] args)
            {
                string vowels = "aeiouy";
    
                Console.Write("Enter some text: ");
                string input = Console.ReadLine();
    
                foreach (var vowelCount in input.Where(c => vowels.Contains(c)).GroupBy(c => c).OrderBy(g => vowels.IndexOf(g.Key)))
                    Console.WriteLine("{0} appears {1} times.", vowelCount.Key, vowelCount.Count());
            }
    My output:
    Code:
    Enter some text: Be careful to not fall into the premature optimization trap. Th
    e real bottleneck is going to be the user input, and unless they type an extreme
    ly large amount of text, the difference between algorithms is going to be incons
    equential
    a appears 12 times.
    e appears 30 times.
    i appears 13 times.
    o appears 14 times.
    u appears 7 times.
    y appears 3 times.
    Press any key to continue . . .
    Last edited by itsme86; 02-23-2012 at 03:11 PM.
    If you understand what you're doing, you're not learning anything.

  4. #4
    Registered User
    Join Date
    Mar 2011
    Posts
    41
    Just to add some numbers to the topic, I ran some speed tests. Using the text from itsme86, and the three methods show (numbered from top to bottom), these were the results:
    Code:
    Method 1 took 35414 milliseconds for 1000000 runs
    Method 2 took 25668 milliseconds for 1000000 runs
    Method 3 took 35571 milliseconds for 1000000 runs
    Unless you are having to do this a lot, there really isn't much of a difference.

  5. #5
    Registered User vohu's Avatar
    Join Date
    Feb 2012
    Posts
    6
    Quote Originally Posted by Momerath View Post
    Just to add some numbers to the topic, I ran some speed tests. Using the text from itsme86, and the three methods show (numbered from top to bottom), these were the results:
    Code:
    Method 1 took 35414 milliseconds for 1000000 runsMethod 2 took 25668 milliseconds for 1000000 runsMethod 3 took 35571 milliseconds for 1000000 runs
    Unless you are having to do this a lot, there really isn't much of a difference.
    Method 2 is faster, about 1/3, 1/4 ... it's not negligible for a lot of processing

  6. #6
    Registered User
    Join Date
    Mar 2011
    Posts
    41
    Quote Originally Posted by vohu View Post
    Method 2 is faster, about 1/3, 1/4 ... it's not negligible for a lot of processing
    How often do you have to count the vowels in a block of text?

  7. #7
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    And again, you're waiting for the user to enter the text. And unless they're entering hundreds of thousands of characters of text, the processing time won't even be noticeable.
    If you understand what you're doing, you're not learning anything.

  8. #8
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607
    I would prefer foreach over for and in most cases readability over performance. The fact is that the difference between those two snippets is next to nil and not worth worrying about. However the lack of the usage of generics, interfaces, foreach, and other constructs that make life so much simpler should raise a red flag.

  9. #9
    Registered User
    Join Date
    Feb 2012
    Posts
    3
    Quote Originally Posted by itsme86 View Post
    Code:
    OrderBy(g => vowels.IndexOf(g.Key)
    Thanks for your answer, just another one question on this code.

    I don't understand this line ? What does it mean ? "g" is a method of "vowels", right ?

  10. #10
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    The argument to OrderBy() is called a lambda expression. Lambda expressions are basically a quick and easy in-line delegate.

    "g" is just a variable name I pulled out of thin air. I used "g" to represent "group". Check out GroupBy() for more information on the GroupBy() method and OrderBy() for more information on the OrderBy() method. And of course, Lambda Expressions (C# Programming Guide) will explain what lambda expressions are.

    Without lambdas you'd have to do something like this:
    Code:
    static string vowels = "aeiouy";
    
    static void Main(string[] args)
    {
        Console.Write("Enter some text: ");
        string input = Console.ReadLine();
    
        foreach (var vowelCount in input.Where(MyWherePredicate)).GroupBy(MyGroupBySelector).OrderBy(MyOrderByMethod))
            Console.WriteLine("{0} appears {1} times.", vowelCount.Key, vowelCount.Count());
    }
    
    private static bool MyWherePredicate(char c)
    {
        return vowels.Contains(c);
    }
    
    private static char MyGroupBySelector(char c)
    {
        return c;
    }
    
    private static int MyOrderByMethod(IGrouping<char, char> g)
    {
        return vowels.IndexOf(g.Key);
    }
    Last edited by itsme86; 02-27-2012 at 11:57 AM.
    If you understand what you're doing, you're not learning anything.

  11. #11
    Registered User
    Join Date
    Feb 2012
    Posts
    3
    I understand now with yours links.
    About Lambda Expressions, I've never heard of them, thanks to you, I discovered them.



Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Calculate Execution Time?
    By infantheartlyje in forum C Programming
    Replies: 11
    Last Post: 10-14-2011, 02:01 PM
  2. execution time
    By shuo in forum C++ Programming
    Replies: 3
    Last Post: 10-17-2007, 02:58 AM
  3. Execution Time in Microseconds?
    By thetinman in forum C++ Programming
    Replies: 11
    Last Post: 06-02-2007, 01:32 PM
  4. measuring time of execution
    By KevBin in forum C Programming
    Replies: 6
    Last Post: 12-02-2004, 02:08 PM