You can measure the time it takes to read or write a largefile in C# using the
Stopwatch class from System.Diagnostics. Here's how to do it for both read and write operations:
Measure File Read Time
using System;
using System.Diagnostics;
using System.IO;
public class FileReadTimer
{
public static void MeasureReadTime(string filePath)
{
Stopwatch stopwatch = Stopwatch.StartNew();
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
byte[] buffer = new byte[1024 * 1024]; // 1 MB buffer
while (fs.Read(buffer, 0, buffer.Length) > 0) { }
}
stopwatch.Stop();
Console.WriteLine($"Read completed in {stopwatch.Elapsed.TotalSeconds} seconds.");
}
}
Measure File Write Time
using System;
using System.Diagnostics;
using System.IO;
public class FileWriteTimer
{
public static void MeasureWriteTime(string filePath, long sizeInMB)
{
Stopwatch stopwatch = Stopwatch.StartNew();
byte[] buffer = new byte[1024 * 1024]; // 1 MB buffer
new Random().NextBytes(buffer); // fill with random data
using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
for (int i = 0; i < sizeInMB; i++)
{
fs.Write(buffer, 0, buffer.Length);
}
}
stopwatch.Stop();
Console.WriteLine($"Write completed in {stopwatch.Elapsed.TotalSeconds} seconds.");
}
}
Notes
Use larger buffers (e.g., 1 MB) for better performance on large files.
For I/O-heavy benchmarks, ensure the disk cache and other system factors are considered.
Always dispose streams properly or use using blocks.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
You can measure the time it takes to read or write a large file in C# using the
Stopwatchclass fromSystem.Diagnostics. Here's how to do it for both read and write operations:Measure File Read Time
Measure File Write Time
Notes
usingblocks.