Search code examples
cubuntuvirtualboxbandwidth

Why can't I write more than 2GB?


I am using this code to measure the writing bandwidth of my computer. The program needs two parameters, the name of the file that we are going to write and the amount of MB.

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/time.h>


int main(int argc, char *argv[]) {
    struct timeval tv0, tv1;
    int chunkSize = 128, res;
    char str[chunkSize];
    
    if (argc != 3)
    perror("Usage: file_name Mb.");
     
    int megabytes = atoi(argv[2]);
    int sizeWrite = megabytes*1024*1024;
    int sizeWriteAux = sizeWrite;

    FILE * fp;
    fp = fopen (argv[1], "w+");

    res = gettimeofday(&tv0, NULL);
    if (res < 0) {
         perror ("gettimeofday");
    }
    
    while (sizeWriteAux > 0) {
     fwrite(str , 1 , chunkSize , fp );
        sizeWriteAux -= chunkSize;
    }
    
    res = gettimeofday(&tv1, NULL);
    if (res < 0) {
         perror ("gettimeofday");
    }
    
    fclose(fp);
    
    double secs = (((double)tv1.tv_sec*1000000.0 + (double)tv1.tv_usec) - ((double)tv0.tv_sec*1000000.0 + (double)tv0.tv_usec))/1000000.0;
    printf("Time: %f \n", secs);
    
    double x = sizeWrite/secs;
    double y = megabytes/secs;
    printf("Bandwith: %f bytes x sec \n", x);
    printf("Bandwith: %f Mbytes x sec \n", y);

    return(0);
}

The program works correctly up to 2047 MB, but as of 2048 it does not write anything and results in infinite bandwidth without returning any error.

I'm running this program on an Ubuntu 20 in VirtualBox, with 12GB RAM and 10 GB of free disk memory.

Does anyone know why this happens?


Solution

  • int megabytes = atoi(argv[2]);
    int sizeWrite = megabytes*1024*1024;
    int sizeWriteAux = sizeWrite;
    

    You're using int. It seems, that on your system sizeof(int) == 4 (bytes). Since int is signed and one bit is for the sign, you can utilize only 31 bits.

    2^31 = 2147483648 (2G)

    If you would have used unsigned int instead, then

    2^32 = 4294967296 (4G)

    What difference a bit can make, right?

    Now imagine, you would have used (long) long int, namely 64 bits.

    And you should be wary about the limit of the file-size of your underlying filesystem. Fat for example has a limit of max 2G for a file.