iattila
iattila

Reputation: 135

Helping optimize function to obtain the file size in a loop

I use this code to open in real time a recording file and use fseek() and ftell() to obtain the file size:

typedef struct _Recording Recording;
struct _Recording
{
    FILE *file;
    long filesize;
    int progress_id;
    ...
};

void start_recording(Recording *recording, char* filepath)
{
        ...         
        recording->file = fopen(filepath, "rb");
        recording->progress_id =
            g_timeout_add (500, (GSourceFunc) progress_timeout, recording);
}

gboolean progress_timeout (Recording *recording)
{
        if (recording->file != NULL)
        {
            fseek(recording->file, 0, SEEK_END);
            recording->filesize = ftell(recording->file);        
        }

        return TRUE;
}

void stop_recording(Recording *recording)
{
        ...
        if (recording->file)
        {
            fclose (recording->file);
            recording->file = NULL;
        }

       if (recording->progress_id != 0)
       {
            g_source_remove (recording->progress_id);
            recording->progress_id = 0;
       }
}

I use this function in a loop (500 ms). Need help to optimize function to be faster.

Efficiency of the code.

UPDATED with loop function

Upvotes: 1

Views: 78

Answers (2)

Clifford
Clifford

Reputation: 93556

The code accesses the file-system; the performance of the file system and physical disk access will dominate. Moreover most of the code that executes will be OS and file-system code, not yours, so no ammount of optimisation of your code is likely to help.

There may be some marginal benefit in using lower-level or OS specific APIs rather then stdio, such as stat() or fstat() for POSIX, or GetFileSizeEx() in Windows for example. These directly get the size rather than using fseek() so are likely to be faster, but perhaps not significantly for the reasons given.

Upvotes: 2

If you do not require "maximal" (questioned) compatibility, it makes sense to use operating system specific functions like fstat. Opening a file has always overhead and even seeking to the end - the operating system tries to anticipate what you're doing and may start caching file contents into memory - in this case needlessly.

Upvotes: 3

Related Questions