Measurement

Measure Ellapsed Milliseconds

using System.Diagnostics;
 
    /// <summary>Write the Elapsed Milliseconds to Trace</summary>
    public class ElapsedMillisecondsTrace : IDisposable
    {
        Stopwatch _stopwatch = new Stopwatch();
 
        /// <summary>Initializes a new instance of the <see cref="ElapsedMillisecondsTrace"/> class.</summary>
        public ElapsedMillisecondsTrace()
        {
            _stopwatch.Start();
        }
 
        /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
        public void Dispose()
        {
            _stopwatch.Stop();
            Trace.WriteLine( _stopwatch.ElapsedMilliseconds);
        }
    }

Example:

using (new EllapsedMilliseconds())
{
    DoWork();
}

Measuring memory delta

public class MemoryDeltaTrace : IDisposable
    {
        long _memorySize;
 
        /// <summary>Initializes a new instance of the <see cref="MemoryDeltaTrace"/> class.</summary>
        /// <param name="text">The text.</param>
        public MemoryDeltaTrace()
        {
            _memorySize = GC.GetTotalMemory(true);
        }
 
        /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
        public void Dispose()
        {
            Trace.WriteLine("Memory Delta" + (GC.GetTotalMemory(true) - _memorySize).ToString());
        }
    }

Example:

using (new MemoryDeltaTrace())
{
    MyLargeObject myLargeObject = new MyLargeObject();
}

Approximate memory measurement

using System.Runtime.Serialization.Formatters.Binary;
 
        /// <summary>Returns serialised size of object in bytes</summary>
        public static long ApproxSizeLarge(object theObject)
        {
            FileInfo fileInfo= new FileInfo(System.IO.Path.GetTempFileName());
 
            BinaryFormatter formatter = new BinaryFormatter();
            using (StreamWriter writer = new StreamWriter(fileInfo.Path);
            {
                formatter.Serialize(writer.BaseStream, theObject);
            }
 
            long length = info.Length;
            info.Delete();
 
            return length;
        }
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License