Free space counter is slow

I am trying to display amount of free space on an SD card on my menu when the operator calls up the menu. I did some test with the following code snippet. I timed it 10 seconds before the free space was displayed. This is pretty long, if someone presses a menu button and waits.

Am I getting something wrong or is it about the right speed? My card is 2GB SD card. Thanks.

unsigned int sd_free_space_MB(SdFat* sdfp)
{
  uint32_t freeMB = sdfp->vol()->freeClusterCount();
  freeMB *= sdfp->vol()->blocksPerCluster();
  freeMB/=2048;
  return freeMB;
}

I timed it 10 seconds before the free space was displayed.

I added timing to the SdFat SdInfo sketch and tried several cards. Here is the SdInfo code:

  uint32_t m = millis();
  uint32_t volFree = vol.freeClusterCount();
  m = millis() - m;
  cout << pstr("millis: ") << m << endl;
  cout << pstr("freeClusters: ") <<  volFree << endl;
  float fs = 0.000512*volFree*vol.blocksPerCluster();
  cout << pstr("freeSpace: ") << fs << pstr(" MB (MB = 1,000,000 bytes)\n");

Here are results with SdInfo's 4 MHz SPI clock:

1.9 seconds for a 4 GB SanDisk class 4 card.

millis: 1900
freeClusters: 97017
freeSpace: 3179.05 MB (MB = 1,000,000 bytes)

0.487 seconds for a 2 GB SanDisk class 2 card.

millis: 487
freeClusters: 59359
freeSpace: 1945.08 MB (MB = 1,000,000 bytes)

0.438 seconds for a 2 GB Dane-Elec Card.

millis: 438
freeClusters: 61357
freeSpace: 2010.55 MB (MB = 1,000,000 bytes)

I ran the test again with a 8 MHz SPI clock.

0.362 seconds for the 2 GB SanDisk card.

millis: 362
freeClusters: 59359
freeSpace: 1945.08 MB (MB = 1,000,000 bytes)

1.403 seconds for the 4 GB SanDisk card.

millis: 1403
freeClusters: 97017
freeSpace: 3179.05 MB (MB = 1,000,000 bytes)

These tests show an interesting fact. Access to FAT16 on the 2 GB cards is faster since the FAT entry size is 16-bits. 4 GB and larger cards have 32-bit FAT entries so twice as much I/O is required. That's why the 4 GB card takes about four times as long as the 2 GB cards.

Often people make the mistake of formatting small card FAT32 and ruin performance.

So always use SD formatter SD Memory Card Formatter for Windows/Mac | SD Association. It will always produce the best results.

NEVER use OS utilities with your idea of what is best for SD card performance.

Here is the 2 GB Dane-Elec card formatted FAT32 with 1 KB clusters on Windows. The SPI speed is 8 MHz.

18.228 seconds.

millis: 18228
freeClusters: 1949567
freeSpace: 1996.36 MB (MB = 1,000,000 bytes)
fatStartBlock: 2559

Hahaha! I am a fool! I should have tried the formatter a while back. I didn't. Now I formatted with it and without timing I noticed it was around 0.5 seconds now.

Thank you so much! Wasted my time programming a message "Analyzing SD free space...". May be useful for larger cards.