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

Shervan360 1,481 Reputation points
2021-11-28T09:02:04.337+00:00

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.
9,936 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,011 Reputation points
    2021-11-28T10:55:22.213+00:00

    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");
    

  2. Bruce (SqlWork.com) 52,491 Reputation points
    2021-11-28T20:07:24.933+00:00

    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