DevTimer 1.0.0
dotnet add package DevTimer --version 1.0.0
NuGet\Install-Package DevTimer -Version 1.0.0
<PackageReference Include="DevTimer" Version="1.0.0" />
<PackageVersion Include="DevTimer" Version="1.0.0" />
<PackageReference Include="DevTimer" />
paket add DevTimer --version 1.0.0
#r "nuget: DevTimer, 1.0.0"
#:package DevTimer@1.0.0
#addin nuget:?package=DevTimer&version=1.0.0
#tool nuget:?package=DevTimer&version=1.0.0
DevTimer
A lightweight, developer-friendly performance profiling utility for .NET applications. DevTimer logs execution time for methods and async tasks using attributes or middleware injection, making it easy to identify performance bottlenecks and optimize application performance.
Features
- Attribute-based timing with
[TimeMethod]
and[TimeAsync]
decorators - Extension methods for easy timing of existing code
- Customizable logging with configurable thresholds and categories
- Async support for proper async/await timing without blocking
- Thread-safe execution timing
- Minimal performance overhead
- Integration ready for popular logging frameworks
Installation
dotnet add package DevTimer
Quick Start
Basic Usage
using DevTimer;
// Simple timing
var timingEngine = new TimingEngine();
var result = timingEngine.Time("MyOperation", () =>
{
// Your code here
return "Operation completed";
}, "Database");
Attribute-Based Timing
public class UserService
{
[TimeMethod("Database")]
public string GetUserData(int userId)
{
// Simulate database call
System.Threading.Thread.Sleep(100);
return $"User data for {userId}";
}
[TimeAsync("API")]
public async Task<string> GetUserDataAsync(int userId)
{
// Simulate async API call
await Task.Delay(200);
return $"User data for {userId}";
}
[TimeMethod("Cache", WarningThresholdMs = 50)]
public string GetCachedData(string key)
{
// Simulate cache lookup
System.Threading.Thread.Sleep(10);
return $"Cached data for {key}";
}
}
Extension Methods
// Time a synchronous operation
var result = TimingExtensions.TimeMethod(() => "Hello World", "MyMethod", "Category");
// Time an asynchronous operation
var asyncResult = await Task.FromResult("Async Hello").TimeMethodAsync("MyAsyncMethod", "Category");
Custom Configuration
// Custom logger
var customLogger = new MyCustomLogger();
var config = new TimingConfig
{
WarningThresholdMs = 500,
EnableDetailedLogging = true
};
var timingEngine = new TimingEngine(customLogger, config);
Advanced Usage
Custom Logger Implementation
public class MyCustomLogger : ITimingLogger
{
public void LogTiming(TimingResult result)
{
var level = result.ExceededThreshold ? "WARN" : "INFO";
var message = $"[{level}] {result.MethodName}: {result.ElapsedMilliseconds}ms";
// Log to your preferred logging framework
Console.WriteLine(message);
}
}
Threshold Warnings
[TimeMethod("SlowOperation", WarningThresholdMs = 1000)]
public void SlowOperation()
{
// This will trigger a warning if it takes longer than 1 second
System.Threading.Thread.Sleep(1500);
}
Exception Handling
DevTimer properly handles exceptions and logs timing information even when operations fail:
var result = timingEngine.Time("RiskyOperation", () =>
{
throw new InvalidOperationException("Something went wrong");
}, "ErrorHandling");
Configuration Options
TimingConfig Properties
Property | Type | Default | Description |
---|---|---|---|
WarningThresholdMs |
long |
1000 |
Threshold in milliseconds for warning logs |
EnableDetailedLogging |
bool |
true |
Enable detailed timing information |
LogExceptions |
bool |
true |
Log timing information for exceptions |
DefaultCategory |
string |
"Default" |
Default category for untagged operations |
TimingResult Properties
Property | Type | Description |
---|---|---|
MethodName |
string |
Name of the timed method |
Category |
string |
Category of the operation |
ElapsedMilliseconds |
long |
Execution time in milliseconds |
ElapsedTicks |
long |
Execution time in ticks |
IsAsync |
bool |
Whether the operation was async |
StartTime |
DateTime |
When the operation started |
EndTime |
DateTime |
When the operation ended |
ExceededThreshold |
bool |
Whether the operation exceeded the warning threshold |
AdditionalInfo |
string |
Additional information (e.g., exception details) |
Performance Considerations
- Minimal overhead: DevTimer adds minimal performance overhead to your operations
- Thread-safe: Safe for concurrent execution
- Memory efficient: No memory leaks or excessive allocations
- Configurable: Adjust logging levels and thresholds as needed
Integration Examples
ASP.NET Core Middleware
public class TimingMiddleware
{
private readonly RequestDelegate _next;
private readonly TimingEngine _timingEngine;
public TimingMiddleware(RequestDelegate next)
{
_next = next;
_timingEngine = new TimingEngine();
}
public async Task InvokeAsync(HttpContext context)
{
await _timingEngine.TimeAsync($"HTTP_{context.Request.Method}_{context.Request.Path}",
async () => await _next(context), "HTTP");
}
}
Entity Framework Integration
public class TimedDbContext : DbContext
{
private readonly TimingEngine _timingEngine = new TimingEngine();
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
return await _timingEngine.TimeAsync("SaveChanges",
async () => await base.SaveChangesAsync(cancellationToken), "EF");
}
}
Logging Framework Integration
public class SerilogTimingLogger : ITimingLogger
{
private readonly ILogger _logger;
public SerilogTimingLogger(ILogger logger)
{
_logger = logger;
}
public void LogTiming(TimingResult result)
{
var level = result.ExceededThreshold ? LogEventLevel.Warning : LogEventLevel.Information;
_logger.Write(level, "{MethodName} took {ElapsedMs}ms",
result.MethodName, result.ElapsedMilliseconds);
}
}
Best Practices
- Use meaningful method names for better log readability
- Categorize operations to group related timing information
- Set appropriate thresholds based on your application's performance requirements
- Monitor in production to identify real-world performance issues
- Combine with APM tools for comprehensive performance monitoring
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
For support, please open an issue on GitHub or contact us at support@agicoders.com.
Made with ❤️ by Agicoders
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net8.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
Version | Downloads | Last Updated |
---|---|---|
1.0.0 | 484 | 7/23/2025 |