strcat is a very expensive function. It must loop through every character in the current string to find the end before adding the new content. Similar to my advice against using strlen in a loop, you should avoid using strcat in a loop. Let's do some rough calculations based on your code:
Code:
Outer Loop:
(0xCFF0 / 0x10) * 3 = 9,981 strcat calls | 26,616 characters outputted
Inner Loop:
(0xCFF0 / 0x10) * 8 * 3 = 79,848 strcat calls | 239,544 characters outputted
Total strcat calls: 89,829
Total Characters: 266,170
From this we can get an idea of the total number of iterations performed in the strcat calls. 89,829 strcat calls iterating over an average of 133,085 (half of 266,170) characters each time:
Code:
89,829 * 133,085 = 11,954,892,465
That's over eleven billion wasted iterations! You can see why it takes a long time! Now, if we can remove those strcat calls, we will speed up the code by several orders of magnitude. We can do this by keeping our current position in a variable.
We can use a cur_pos pointer:
Code:
char* cur_pos = memory;
for (int base = 0; base <= 0xCFF0; base += 0x10)
{
sprintf(cur_pos, "%04X", base);
cur_pos += 4;
strcpy(cur_pos, ": ");
cur_pos += 2;
for (int a = 0; a <= 0x0E; a += 2)
{
sprintf(cur_pos,"%02X%02X", (unsigned char) ram[base + a],
(unsigned char) ram[base + a + 1]);
cur_pos += 4;
strcpy(cur_pos, " ");
cur_pos += 1;
}
strcpy(cur_pos, "\r\n");
cur_pos += 2;
}
Or, alternatively, we can use cur_pos as an array index:
Code:
size_t cur_pos = 0;
for (int base = 0; base <= 0xCFF0; base += 0x10)
{
sprintf(&memory[cur_pos], "%04X", base);
cur_pos += 4;
strcpy(&memory[cur_pos], ": ");
cur_pos += 2;
for (int a = 0; a <= 0x0E; a += 2)
{
sprintf(&memory[cur_pos], "%02X%02X", (unsigned char) ram[base + a],
(unsigned char) ram[base + a + 1]);
cur_pos += 4;
strcpy(&memory[cur_pos], " ");
cur_pos += 1;
}
strcpy(&memory[cur_pos], "\r\n");
cur_pos += 2;
}