Last active
December 15, 2021 16:30
-
-
Save jamescurran/dbb537c68d2fd898178b4b3d4ef6f290 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Copyright (c) 2019-2020 James M. Curran/Novel Theory LLC. All rights reserved. | |
// Licensed under the Apache License, Version 2.0. | |
// See License.txt in the project root for license information. | |
using System; | |
using System.Diagnostics; | |
using Microsoft.Extensions.Logging; | |
namespace NovelTheory.Common | |
{ | |
// | |
public class TimeThis : IDisposable | |
{ | |
private string _msg; | |
private Stopwatch _sw; | |
private ILogger _logger; | |
public TimeThis(ILogger logger, string msg= null) | |
{ | |
_msg = msg ?? ""; | |
_logger = logger; | |
_logger.LogInformation("Start:" + msg); | |
_sw = new Stopwatch(); | |
_sw.Start(); | |
} | |
public void Dispose() | |
{ | |
_sw.Stop(); | |
_logger.LogInformation($"Complete:{_msg}: Elapsed: {_sw.Elapsed}"); | |
} | |
} | |
public static class TimeThisExt | |
{ | |
public static TimeThis TimeThis(this ILogger logger, string msg = null) | |
=> new TimeThis(logger, msg); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good idea! Thanks.
A suggestion: You can completely eliminate memory allocations and make it 3× faster:
TimeThis
does not have to be aclass
; make it astruct
Benchmark results: