Bush
Bush

Reputation: 2533

Open file for 'write' takes 10-50 times more time than open file for 'read'

I made some cpp app that make statistics on i/o operations on external sd card in Android device.

I noticed that if I open file for read purpose it take few tens microseconds - for example 138 microseconds and for write purpose it takes 5265 microseconds, which is 38 times bigger.

Why is that?

EDIT: in the 'O_WRONLY' case - the file is not exist before.

My specific code looks like:

int fd = open(file_name, O_RDONLY);

And

int fd = open(tmp_name,O_CREAT|O_TRUNC|O_WRONLY);

Upvotes: 0

Views: 508

Answers (2)

Olaf Dietsche
Olaf Dietsche

Reputation: 74108

Truncation means probably modifying SD Card contents. If the truncated file is very large this could take some time.

File creation involves a write to SD Card anyway, so it definitely is slower than just reading. Another factor, which influences write speed, is the SD Card's age. If there have been many writes, even small ones, the search for a new unused block could consume quite some time.

Upvotes: 1

NPE
NPE

Reputation: 500923

If the file exists, in the second case it has to be truncated. This requires extra work, and could well explain the difference.

If the file doesn't exist, the first call would fail and the second would create the file. Creating the file requires work and is slower than simply discovering that it's not there.

Upvotes: 2

Related Questions