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

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

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.
6,911 questions
{count} votes

2 answers

Sort by: Most helpful
  1. answered 2021-11-28T10:55:22.213+00:00
    Karen Payne MVP 29,126 Reputation points Microsoft MVP

    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. answered 2021-11-28T20:07:24.933+00:00
    Bruce (SqlWork.com) 27,936 Reputation points

    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.

    No comments