Logarithm logarithmically 1, 10, 100, 1000, etc.

Is there a more efficient way to do the following, is there something just wrong with this? I am looking for the most efficient way of logging logarithmically.

public bool Read() { long count = Interlocked.Increment(ref _count); switch (count) { case 1L: case 10L: case 100L: case 1000L: case 10000L: case 100000L: case 1000000L: case 10000000L: case 100000000L: case 1000000000L: case 10000000000L: case 100000000000L: case 1000000000000L: case 10000000000000L: case 100000000000000L: case 10000000000000000L: case 100000000000000000L: case 1000000000000000000L: _logger.LogFormattable(LogLevel.Debug, $"{count} Rows Read"); break; } return _reader.Read(); } 

Update:

Here are my tests for micro tests.

  • Method 1: Übercoder stateful method
  • Method2: My path using a large operator
  • Method 3: the Marcus Weninger path with good math function

Since for me, 100 million records that are read without registration take about 20 minutes, and the additional 4 seconds is nothing. I am going to do something with a wonderful mathematical way. Mathod3 wins in my scenario.

 Run time for 100,000,000 iterations averaged over 100 attempts Method1 Max: 00:00:00.3253789 Method1 Min: 00:00:00.2261253 Method1 Avg: 00:00:00.2417223 Method2 Max: 00:00:00.5295368 Method2 Min: 00:00:00.3618406 Method2 Avg: 00:00:00.3904475 Method3 Max: 00:00:04.0637217 Method3 Min: 00:00:03.2023237 Method3 Avg: 00:00:03.3979303 
+5
source share
2 answers

If performance is not a big issue, I would use the following

 if(Math.Log10(count) % 1 == 0) _logger.LogFormattable(LogLevel.Debug, $"{count} Rows Read"); 

This question reads as follows:

For floating point numbers, n% 1 == 0 is usually a way to check if there is anything beyond the decimal point.


Edit: to complete my answer, you can also track the following registration value, as @ Übercoder sent in his answer.

 long nextLoggingValueForLogX = 1; if (count == nextLoggingValueForLogX ) { nextLoggingValueForLogX *= 10; // Increase it by your needs, eg, logarithmically by multiplying with 10 _logger.LogFormattable(LogLevel.Debug, $"{count} Rows Read"); } 

However, this method will have a new variable for each log, which should not be executed every time. This will add extra code as well as extra work if it should be thread safe.

+8
source
 static long logTrigger = 1; if (count == logTrigger) { logTrigger *= 10; // do your logging } 
+3
source

Source: https://habr.com/ru/post/1242917/


All Articles