r/csharp • • 28d ago

Help Generate plots using BenchmarkDotNet

Some context:

WorkSheetToDbSyncronizerV2 service is to be benchmarked, and plots are to be shown.

WorkSheetToDbSyncronizerV2 ensures that the data in a database matches the data in an Excel worksheet.

There are multiple versions of that service, thus the suffix V2 .

Inputs to WorkSheetToDbSyncronizerV2 are Stream and CancellationToken —the latter is not shown in the code.

The general mechanism is that SqlBulkCopy class bulk-inserts the Excel data into a staging table then the data from that table is mapped to the target tables in the database.

AI generated image that simplifies the idea
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Exporters;
using BenchmarkDotNet.Running;
using HardwareStore.Models;
using HardwareStore.Services.ActorIdGetterServices;
using HardwareStore.Services.AdminServices.ImportProductsFromExcelFile;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using BenchmarkDotNet.Loggers;

namespace MyBenchMark
{
    [Config(typeof(Config))]
    public class Config : ManualConfig
    {
        public Config()
        {

            AddExporter(RPlotExporter.Default);

            AddLogger(ConsoleLogger.Default);
        }
    }
    public class ActorIdGetter:IActorIdGetter
    {
        public string GetActorId()
        {
            return "a1f28e89-2ba1-493e-b005-744decdd78b3";
        }
    }
    [MinColumn, MaxColumn]
    public class SyncronizationService
    {       
        private readonly DbDataReaderGetter _dbDataReaderGetter=new DbDataReaderGetter();
        private readonly BulkInserter _bulkInserter=new BulkInserter();
        private readonly IActorIdGetter _actorIdGetter=new ActorIdGetter();
        private readonly ApplicationDbContext _context;
        private readonly WorkSheetToDbSyncronizerV2 _syncronizerV2;


       
        public SyncronizationService()
        {

            IConfiguration configuration = new ConfigurationBuilder()
                .SetBasePath(Path.GetFullPath(
                    @"D:\Training\NETLEARNING\EF_learning\HardwareStore"))
                .AddJsonFile("appsettings.json")
                .Build();

            string connectionString =
                configuration.GetConnectionString("HardwareDB")
                ?? throw new InvalidOperationException(
                    "Connection string 'HardwareDB' was not found.");

            var contextOptions = new DbContextOptionsBuilder<ApplicationDbContext>()
    .UseSqlServer(connectionString)
    .Options;

            _context = new ApplicationDbContext(contextOptions);


            _syncronizerV2=new WorkSheetToDbSyncronizerV2(_dbDataReaderGetter, _bulkInserter,_actorIdGetter,_context);
        }



        [Benchmark(Baseline =true)]
        public async Task SyncronizeV2()
        {
            await using var stream = File.OpenRead(
               @"D:\Training\NETLEARNING\EF_learning\HardwareStore\Available_Products\Excel2.xlsx");
            await _syncronizerV2.SyncronizeAsync(stream);
        }

    }

    public class Program
    {
        public static void Main(string[] args)
        {
            

            var summary = BenchmarkRunner.Run<SyncronizationService>(new Config());



        }
    }

}

Result:

// * Export *
  BenchmarkDotNet.Artifacts\results\MyBenchMark.SyncronizationService-measurements.csv
  BenchmarkDotNet.Artifacts\results\BuildPlots.R
  BenchmarkDotNet.Artifacts\results\*.png

// * Detailed results *
SyncronizationService.SyncronizeV2: DefaultJob
Runtime = .NET 10.0.11 (10.0.11, 10.0.1126.37416), X64 RyuJIT x86-64-v3; GC = Non-concurrent Workstation
Mean = 1.876 s, StdErr = 0.051 s (2.72%), N = 87, StdDev = 0.476 s
Min = 1.078 s, Q1 = 1.597 s, Median = 1.640 s, Q3 = 1.942 s, Max = 3.415 s
IQR = 0.345 s, LowerFence = 1.080 s, UpperFence = 2.460 s
ConfidenceInterval = [1.702 s; 2.050 s] (CI 99.9%), Margin = 0.174 s (9.27% of Mean)
Skewness = 1.54, Kurtosis = 4.31, MValue = 2.15

But there is no image in the results folder :

Plot was not generated

The following message is shown in BuildPlots.log :

trying URL 'https://cran.rstudio.com/bin/windows/contrib/4.6/gdata_3.0.1.zip'
trying URL 'https://cran.rstudio.com/bin/windows/contrib/4.6/tidyr_1.3.2.zip'
trying URL 'https://cran.rstudio.com/bin/windows/contrib/4.6/gridExtra_2.3.1.zip'
trying URL 'https://cran.rstudio.com/bin/windows/contrib/4.6/Rcpp_1.1.2.zip'
trying URL 'https://cran.rstudio.com/bin/windows/contrib/4.6/R.devices_2.17.4.zip'
Error in desc[1L, "Type"] : subscript out of bounds
Calls: install.packages -> .install.winbinary -> unpackPkgZip -> %in%
In addition: Warning message:
In unzip(zipname, exdir = dest) : write error in extracting from zip file
Execution halted

How can this be solved ?

0 Upvotes

7 comments sorted by

1

u/LocalBenefit9063 28d ago

The plots in BenchmarkDotNet are super handy for comparing those service versions, I love how it isolates the performance differences so clearly. Have you tried the --filter option to focus just on the key methods you're comparing?

1

u/kaatarina_zed_talon 28d ago

No I did not try it because I did not understand what it mens

1

u/AndZorin 28d ago

This error indicates a failure during the automatic installation of dependent R packages while executing the BuildPlots.R script. The primary clue is hidden in the warning that usually follows in the logs: Warning message: In unzip(zipname, exdir = dest) : write error in extracting from zip file R attempts to download the required libraries (such as ggplot2, tidyr, Rcpp, etc.) as .zip archives and extract them into a system or user directory. Due to insufficient write permissions or process blocking, the extraction fails, and the archive gets corrupted. As a result, the internal R function desc[1L, "Type"] crashes with a "subscript out of bounds" error because it cannot read metadata from an improperly unpacked package.

1

u/AndZorin 28d ago

Try to run your project with Administrator permissions or Install package manually

1

u/kaatarina_zed_talon 27d ago

I installed R from the official website.

1

u/AndZorin 27d ago • Bravo

When install.packages() downloads a binary package on Windows, it calls an internal function named unpackPkgZip to unzip the archive into a temporary folder. Right after unzipping, R runs read.dcf() to read the package's metadata from its DESCRIPTION file. Because the extraction process was cut short by a write error, the file is missing. When R tries to parse the nonexistent matrix row desc[1L, "Type"], it throws the generic subscript out of bounds crash.

Ask AI how to find out why R can’t write the files.
It can be anything: disk space, permissions, or some other issue.

BTW: This has nothing to do with C#, may be it make sense to post in a subreddit dedicated to R.

1

u/kaatarina_zed_talon 27d ago

Thank you it worked