divmod10() : a fast replacement for /10 and %10 (unsigned)

I added another measurement to the test program.

With Stimmer's optimization:

Speed = 3.84 us/digit, 6.16 us/byte

The us/digit measures only the speed Print converts the 32 bit integer to a string.

The us/byte measures the entire time to put all the data into the transmit buffer.

extern uint32_t usec_print;

void setup() {
  uint32_t begin_us, end_us;
  Serial.begin(115200);
  Serial.println("Benchmark print integer speed:");
  begin_us = micros();
  Serial.print(1073741824ul);
  Serial.print(1018195846ul);
  Serial.print(1820728843ul);
  Serial.print(2904720785ul);
  Serial.print(3678923723ul);
  Serial.print(4152282824ul);
  Serial.print(1875627853ul);
  Serial.print(2532822983ul);
  Serial.println(3519086527ul);
  Serial.println(4023424234ul);
  end_us = micros();
  Serial.print("Speed = ");
  Serial.print((float)usec_print / 100.0);
  Serial.print(" us/digit, ");
  Serial.print((float)(end_us - begin_us) / 100.0);
  Serial.println(" us/byte");
}

void loop() {}

Print.cpp and Print.h are the same as #77.

I tried to bring use them on Arduino Uno, but it seems my Print and header file arrangement has diverged too far from Arduino's over the years.

Many users need faster decimal print for logging data to SD cards. The big problem with Print is this line

  return write(str);

A class derived from Print may have a fast write for strings but it is not uses since Print defines these members

size_t write(const char *str) {
      if (str == NULL) return 0;
      return write((const uint8_t *)str, strlen(str));
    }

size_t Print::write(const uint8_t *buffer, size_t size)
{
  size_t n = 0;
  while (size--) {
    n += write(*buffer++);
  }
  return n;
}

So printNumber uses the above write(const char *str) and the string is written character at a time.

I did a test with the new version of print. It is faster but not as much as one would expect.

I timed this loop

  for (int i = 0; i < 20000; i++) {
    file.println(i);
  }

The result for the old print is:

Time 9.38 sec
File size 128.89 KB
Write 13.74 KB/sec

For the new print with Stimmer's optimization.

Time 6.00 sec
File size 128.89 KB
Write 21.50 KB/sec

For a simple printField() function with no optimized divide that uses SdFat's write(const char*)

Time 2.66 sec
File size 128.89 KB
Write 48.44 KB/sec

So the improvement in Print will not be fully realized as long as printNumber uses Print::write(const char*).

I believe there is a way to fix this in a class derived from Print since size_t Print::write(const char *str) is not pure virtual. Correct me if I am wrong.

fat16lib:
So printNumber uses the above write(const char *str) and the string is written character at a time.

If the SD library implements write(buf, len), then the it's supposed to be called instead of the 1-byte-at-a-time fallback in Print.cpp.

Are you using your newer SdFat?

I just tried it here with SD and it's terribly slow. Because I don't have the exact program you used, here's what I tried.

#include <SD.h>

const int chipSelect = 0;

void setup()
{
  Serial.begin(115200);
  while (!Serial) ;
  Serial.print("Initializing SD card...");
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    return;
  }
  Serial.println("card initialized.");
  File dataFile = SD.open("datalog.txt", FILE_WRITE);
  if (dataFile) {
    uint32_t begin_us, end_us;
    begin_us = micros();
    for (int i = 0; i < 20000; i++) {
      dataFile.println(i);
    }
    dataFile.close();
    end_us = micros();
    Serial.print("seconds =  ");
    Serial.print((float)(end_us - begin_us) / 1000000.0);
  }  
}

void loop() {}

Yes but if I declared Print::write(const char*) virtual and put the default definition in Print.cpp I get this improvement.

Old Print

Time 6.85 sec
File size 128.89 KB
Write 18.83 KB/sec

The new Print uses the size_t Print::write(const uint8_t *buffer, size_t size) but SdFat defines

  int write(const void* buf, size_t nbyte);

If I override the Print def of write for the new Print I get:

Time 2.61 sec
File size 128.89 KB
Write 49.40 KB/sec

A big improvement over the old print and no overrides:

Time 9.47 sec
File size 128.89 KB
Write 13.61 KB/sec

I am using a very new version of SdFat, not the 3-4 year old version in SD.h.

I have some extra stuff in my loop to time the max and min print time but commenting it out doesn't change much.

The new SdFat is much faster, it allows flash programming to happen in the SD while the next block buffer is being filled by the Arduino program.

Paul,

I tried your sketch on a Uno with 1.0.5 and get a fast write with SD.h and the new Print. About the same as with the new SdFat. Looks like you don't even need the SdFat improvements at 50 KB/sec.

Initializing SD card...card initialized.
seconds = 2.53

There is another speed optimization to make when you are using divmod10 to convert a long into base-10 digits: Only the first few digits of a 10-digit number need full 32-bit precision. Once the high byte is 0 you only need 24 bit precision (saves at least 10 cycles), then when the two highest bytes are 0 you only need a 16 bit divmod10 (saves over a microsecond). Once the three highest bytes are 0 the 8-bit divmod10 only takes a microsecond, and for the very last digit you don't need to do a division at all.

	  while(n & 0xff000000){divmod10_asm32(n, digit, tmp8);*--p = digit + '0';}
	  while(n & 0xff0000){divmod10_asm24(n, digit, tmp8);*--p = digit + '0';}
	  while(n & 0xff00){divmod10_asm16(n, digit, tmp8);*--p = digit + '0';}
	  while((n & 0xff)>9){divmod10_asm8(n, digit, tmp8);*--p = digit + '0';}
	  *--p = n + '0';

The downside is an increase in code size of about 200 bytes. I've attached a modified Print.cpp including all the assembler macros, my profiling indicates it's 0.5us-1.5us faster per digit on average (which adds up to 7us faster for 5-10 digit numbers). I have not fully tested for accuracy yet.

Print.cpp (13.6 KB)

a well implemented trick - trading space for speed -

There are other tricks possible, not investigated though

Consider the fact that the largest uint32_t < 50000 * 10000 * 10000;
with a divmod10000() one could divide the uint32 in 4digit chunks which can be processed by divmod10_asm16

a divmod1000() might be broader usable

another trick would use a divmod100() to extract 2 digits at a time => fit in a byte. => divmod10_asm8() to split it

I have used the ideas here to improve the speed of logging data to SD cards. I wrote functions to print a numerical field to an SD card that are as much as five times faster than the standard Arduino print.

I am now able to log data from four analog pins on an Uno to an SD at 2000 Hz. This is 8000 ADC values per second. This is near the limit since each conversion takes about 110 microseconds.

I am using a small RTOS, Nil RTOS, written by Giovanni Di Sirio. I ported this RTOS to avr arduinos Google Code Archive - Long-term storage for Google Code Project Hosting..

I wrote a version of analogRead() that sleeps while the ADC conversion occurs. This saves about 90 microseconds of CPU time per conversion.

I have also modified SdFat so it no longer busy waits for flash programming in the SD to complete.

Here are test results for 16-bit unsigned fields and 32-bit float fields.

This test compares the standard print function
with printField. Each test prints 20,000 values.

Test of println(uint16_t)
Time 6.51 sec
File size 128.89 KB
Write 19.80 KB/sec

Test of printField(uint16_t, char)
Time 1.27 sec
File size 128.89 KB
Write 101.33 KB/sec

Test of println(double)
Time 17.17 sec
File size 160.00 KB
Write 9.32 KB/sec

Test of printField(double, char)
Time 3.56 sec
File size 160.00 KB
Write 44.94 KB/sec

Here are the test loops for the writes:

   switch(test) {
    case 0:
      for (uint16_t i = 0; i < N_PRINT; i++) {
        file.println(i);
      }
      break;

    case 1:
      for (uint16_t i = 0; i < N_PRINT; i++) {
        file.printField(i, '\n');
      }
      break;

    case 2:
      for (uint16_t i = 0; i < N_PRINT; i++) {
        file.println((double)0.0001*i, 4);
      }
      break;

    case 3:
      for (uint16_t i = 0; i < N_PRINT; i++) {
        file.printField((double)0.0001*i, '\n', 4);
      }
   }

I have attached the implementation of printField().

PrintField.cpp (8.85 KB)

Impressive numbers, really good !

think divmod10() should become part of the core seeing these and the above numbers.

robtillaart:
think divmod10() should become part of the core seeing these and the above numbers.

I'm planning to release it in the next version of Teensyduino.

Stimmer, is Arduino Print LGPL ok with you? Would you like your name to appear, other than "Stimmer" and link to this forum topic? You deserve credit.... just let me know what should be in the comments?

Credit is not enough. Open source licenses require a copyright claim by Stimmer.

Ok then. I'll hold off publishing anything until Stimmer replies.

I'm currently working on a Mac-related USB problem, so it's not like there's any hurry. But it would be nice to publish this code to a wider audience, if that's allowed?

@Paul
:wink: Shouldn't you be working on a space related issue with the Teensy uploader ]:smiley:
Best regards
Jantje

agree these should be standard libs of the core,

but the arduino team wont,

Yes that's OK. Consider what I wrote to be in the public domain so anyone can use it under any license. Just put something like "this section of code based on public domain code by Stimmer, see post at forum.arduino.cc/whatever-the-url-is ".

agree these should be standard libs of the core,
but the arduino team wont,

I'm definitely not sure of the latter.
The code is not core lib ready yet. For Arduino-team the portability of core libs is a very important issue. The divmod10() function should be decorated with #ifdefs to select the C (portable to DUE?) or the assembly (328 only?) implementation .

So the fun part is over, now the real work starts :wink:

So the fun part is over, now the real work starts

It ought to be pretty simple to surround this code with #ifdef AVR, or perhaps a check for the AVR architecture with multiply? In fact, the Print.cpp I posted has #ifdef checks to use either the original C code, Stimmer's optimization, or your version of the Hackers Delight algorithm. Yes, it requires some careful attention, but this part really isn't very difficult.

Whether the Arduino Team will accept this for the Print.cpp that ships for all Arduino boards is a good question. Historically, they've been pretty uninterested in speed optimizations.

I definitely do plan to publish this in the next version of Teensyduino, likely within the next 6 weeks. Of course, if Coding Badly is satisfied with the licensing? ... Thanks Stimmer! :smiley: You definitely did the heavy lifting with an amazing optimization!

Good enough for me.