BUPT-homework/semester3/exercises/exercise2.6.c

117 lines
1.7 KiB
C
Raw Normal View History

2022-09-12 16:56:48 +08:00
#include <stdio.h>
#include <time.h>
int counter = 0;
void getTime(int N, clock_t start_t, time_t end_t) {
double runningTime;
runningTime = ((double) (end_t - start_t)) / CLOCKS_PER_SEC;
printf("%d: Took %lf sec\n", counter++, runningTime);
}
void test(int N) {
clock_t start_t;
clock_t end_t;
int sum;
// 1
sum = 0;
start_t = clock();
for (int i = 0; i < N; i++) {
sum++;
}
end_t = clock();
getTime(N, start_t, end_t);
// 2
start_t = clock();
sum = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
sum++;
}
}
end_t = clock();
getTime(N, start_t, end_t);
// 3
start_t = clock();
sum = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N * N; j++) {
sum++;
}
}
end_t = clock();
getTime(N, start_t, end_t);
// 4
start_t = clock();
sum = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < i; j++) {
sum++;
}
}
end_t = clock();
getTime(N, start_t, end_t);
// 5
start_t = clock();
sum = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < i * i; j++) {
for (int k = 0; k < j; k++) {
sum++;
}
}
}
end_t = clock();
getTime(N, start_t, end_t);
// 6
start_t = clock();
sum = 0;
for (int i = 1; i < N; i++) {
for (int j = 1; j < i * i; j++) {
if (j % i == 0) {
for (int k = 0; k < j; k++) {
sum++;
}
}
}
}
end_t = clock();
getTime(N, start_t, end_t);
}
int main(void) {
int times[] = {5, 10, 100, 250};
for (int i = 0; i < 4; i++) {
counter = 0;
printf("N = %d\n\n", times[i]);
test(times[i]);
printf("\n");
}
}