Share via

How can I measure which one is faster? - C#

Shervan360 1,661 Reputation points
Nov 28, 2021, 9:02 AM

Hello,

I wrote a program with two approaches. How can I measure which one is faster?

Thank you

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace HelloWorld
{

    class Program
    {
        static void Main(string[] args)
        {
            string path = @"G:\";
            ShowBasedSized(path);
            Console.WriteLine();
            ShowBasedSizedWithLinq(path);
        }

        private static void ShowBasedSizedWithLinq(string path)
        {
            var result = from file in new DirectoryInfo(path).GetFiles()
                         orderby file.Length
                         select file;

            foreach (var item in result)
            {
                Console.WriteLine($"{item.Name,-30} - {item.Length,10}");
            }

        }

        private static void ShowBasedSized(string path)
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(path);
            FileInfo[] fileInfos = directoryInfo.GetFiles();

            Array.Sort(fileInfos, new SortFilesBasedSized());

            foreach (FileInfo item in fileInfos)
            {
                Console.WriteLine($"{item.Name,-30} - {item.Length,10}");
            }
        }


    }
    public class SortFilesBasedSized : IComparer<FileInfo>
    {
        public int Compare(FileInfo first, FileInfo second)
        {
            return first.Length.CompareTo(second.Length);
        }
    }
}
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,340 questions
{count} votes

2 answers

Sort by: Newest
  1. Bruce (SqlWork.com) 72,356 Reputation points
    Nov 28, 2021, 8:07 PM

    The main difference, is linq orderby and array sort uses different algorithms. Linq uses a stable quick sort so it can be applied multiple times, and array sort uses different algorithms based on size. Both of these sorts speed is effected by the data (how random the key is and the number of keys).

    As suggested, the directory lookup is the most expensive operations, making the sort time mote.

    0 comments No comments

  2. Karen Payne MVP 35,556 Reputation points
    Nov 28, 2021, 10:55 AM

    Use a StopWatch

    Stopwatch stopwatch = Stopwatch.StartNew();
    // call your method
    stopwatch.Stop();
    
    Debug.WriteLine($"Time taken: {stopwatch.Elapsed.TotalMilliseconds} ms" );
    
    stopwatch.Reset();
    stopwatch.Start();
    // next method
    Debug.WriteLine($"Time taken: {stopwatch.Elapsed.TotalMilliseconds} ms");
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.