使用 BenchmarkDotnet 測試代碼性能

先來點題外話,清明節前把工做辭了(去 tm 的垃圾團隊,各類拉幫結派、勾心鬥角)。此次找工做就得慢慢找了,不能急了,但願能找到個好團隊,好崗位吧。順便這段時間也算是比較閒,也能學習一下和填掉手上的坑。html

說實話很久沒寫博客了,一個是手上的工做確實忙,第二個是還有各類各樣的坑。寫本文的緣由也是由於手上的一個坑——ImageEx,WPF/UWP 上的圖片緩存控件。算法

 

在我寫的這個圖片緩存控件中,其中有一個地方就是要根據圖片的 url 地址,而後來存儲或者獲取本地的圖片文件的。可是呢,咱們不可能把 url 看成本地文件的文件名的,一個是可能包含非法字符(如斜槓),另外一個是長度可能超出限制。想了一下,那就只能用哈希(hash)來解決了,其中 MD5 和 SHA1 兩種算法我以爲均可以解決這個問題。但問題是,哪個更好、更快呢?傳統經驗告訴我是 MD5,可是我以爲仍是有必要手動實踐一下,畢竟沒有 100% 的把握。緩存

先編寫出以下的代碼:app

public static class HashHelper
{
    public static string GetMD5(string input)
    {
        if (input == null)
        {
            throw new ArgumentNullException(nameof(input));
        }

        using (var md5 = MD5.Create())
        {
            var buffer = Encoding.UTF8.GetBytes(input);
            var hashResult = md5.ComputeHash(buffer);
            return BitConverter.ToString(hashResult).Replace("-", string.Empty);
        }
    }

    public static string GetSHA1(string input)
    {
        if (input == null)
        {
            throw new ArgumentNullException(nameof(input));
        }

        using (var sha1 = SHA1.Create())
        {
            var buffer = Encoding.UTF8.GetBytes(input);
            var hashResult = sha1.ComputeHash(buffer);
            return BitConverter.ToString(hashResult).Replace("-", string.Empty);
        }
    }
}

做用是輸入一個字符串,輸出一個哈希後的字符串。性能

 

創建一個 .net core 的控制檯項目,我就叫 TestBenchmarkDotnet。學習

而後安裝 nuget 包,BenchmarkDotnet。測試

QQ截圖20180408222314

安裝完成後編寫以下代碼:url

public class TestContext
{
    [Benchmark]
    public void TestMD5()
    {
        HashHelper.GetMD5("https://www.baidu.com/img/bd_logo1.png");
    }

    [Benchmark]
    public void TestSHA1()
    {
        HashHelper.GetSHA1("https://www.baidu.com/img/bd_logo1.png");
    }
}

而後修改 Main 方法:spa

public class Program
{
    public static void Main(string[] args)
    {
        Summary summary = BenchmarkRunner.Run<TestContext>();
        Console.ReadLine();
    }
}

最後將 Debug 調成 Release 模式,不調試啓動。.net

稍微等待一下子就會出現結果了。

QQ截圖20180408223415

結論是 MD5 確實比 SHA1 快。

另外因爲這是在 .net core 下的測試結果,而 WPF 是跑在 .net framework 下的,那麼是否結果可能不同呢?

Benchmark 支持多個 .net 環境的性能測試(.net framework, net core, mono)。

修改 TestContext 類的代碼:

[ClrJob, CoreJob]
public class TestContext
{
    [Benchmark]
    public void TestMD5()
    {
        HashHelper.GetMD5("https://www.baidu.com/img/bd_logo1.png");
    }

    [Benchmark]
    public void TestSHA1()
    {
        HashHelper.GetSHA1("https://www.baidu.com/img/bd_logo1.png");
    }
}

添加了 ClrJob 和 CoreJob 兩個標籤

而後修改項目的 csproj 文件

<TargetFramework>netcoreapp2.0</TargetFramework>

一行改成

<TargetFrameworks>netcoreapp2.0;net471</TargetFrameworks>

回到 VS 從新編譯,還原 nuget 包。

不調試啓動。稍等片刻。

QQ截圖20180408230358

可見在 .net framework 環境下,仍然是 MD5 比 SHA1 快的。並且能夠看見 .net core 比 .net framework 環境下快了不少。

另外在輸出目錄下,BenchmarkDotnet 會輸出性能測試結果文件:

QQ截圖20180408230657

打開 html 版本後看到的跟剛纔控制檯的是同樣的

QQ截圖20180408230743

相關文章
相關標籤/搜索