I have subtitles /srt files with data being generated by the second. I am trying to extract the data from them and save them to text files in a while(1) loop, its a simple text read and write operation.
But i have found out using fgets to traverse through the file is causing this simple operation to have very high cpu usage ( top command ref). more the number of fgets higher the cpu usage.
The code bit:
int convert_to_txt(FILE *f1, FILE *f2) {
static int str_len = 0;
char cap_nxt_tmp[128];
while (fgets(cap_nxt_tmp, 128, f1) != NULL) {
fprintf(f2, "%s\n", cap_nxt_tmp);
}
return 0;
}
int main(int argc, char* argv[]) {
FILE *inputFilePtr;
FILE *outputFilePtr;
char inputPath[1024] = "storage/sample.srt";
char outputPath[1024] = "storage/sample.txt";
while (1) {
outputFilePtr = fopen(outputPath, "w");
inputFilePtr = fopen(inputPath, "r");
if (inputFilePtr == NULL || outputFilePtr == NULL) {
perror("Error");
}
convert_to_txt(inputFilePtr, outputFilePtr);
fclose(inputFilePtr);
fclose(outputFilePtr);
// theres a break on an end condition lets say least run time is an hour.
}
return 0;
}
i cant understand whats wrong in the way i am using fgets to read the srt/captions file ( 1-2 mb per file), a simple text file i/o/read operation should not consume too much cpu usage.
this basic file i/o in a while(1) of a language like python shows only a 2-3% cpu usage. but this in c is showing about 30% cpu usage. How can i reduce the cpu usage without using sleep . is there any less cpu alternative to fgets?
I don't see anything wrong or strange here.
Your main while(1)
loop never stops, which means you're converting your files over and over again. Files get cached by the OS, so you're not really accessing your physical drives. The program therefore spends almost all the CPU time doing strlen(cap_nxt_tmp)
, and you observe very high CPU load.