Why is my code so slow?

I'm working on a exercise, which has a time to compile limit. Im not looking for any other way to solve this problem, but an explanation. Why is this code so slow? 0.001s it's quite high isn't it? Is there any mistake?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <time.h>
#include <windows.h>
#include <iomanip>

clock_t start,stop;
double czas;

using namespace std;

int main()
{
    int ile;cin>>ile;cin.ignore();
    for(int i=0;i<ile;i++)
    {
        char x[21];
        cin.getline(x,21);
        start=clock();
        for(int f=1;f<21;f+=2)
        {
            if(x[f]==char (71))
                cout<<char (x[f-1]+31);
            if(x[f]==char (72))
                cout<<char (x[f-1]+47);
        }
        stop=clock();
        czas=(double) (stop-start) / CLOCKS_PER_SEC;
        cout<<endl;
        cout<<setprecision(100)<<czas;
    }
    return 0;
}
I wouldn't worry about it. 1 ms is a very short time period and the timer might not even be able to measure it accurately.
You are declaring char x[21] inside a for-loop. Place it one line above it and see what happens.
Though I think Peter87 is right, within the timed section is a cout statement. I expect the cout itself is much slower than any of the other code. In any calculation-intensive code, I would avoid input/output completely, store the result somewhere else instead, and defer the i/o until after calculation is complete.
Topic archived. No new replies allowed.