#include <iostream>
static const int LOOP = 10000000;
static const int N = 10;
void test_if_else() {
for (int i = 0;i < LOOP;i++) {
int sum = 0;
for (int k = 0;k < N;k++) {
if (0 == k) {
sum = sum + 1;
}
else if (1 == k) {
sum = sum + 2;
}
else if (2 == k) {
sum = sum + 3;
}
else if (3 == k) {
sum = sum + 3;
}
else if (4 == k) {
sum = sum + 4;
}
else if (5 == k) {
sum = sum + 5;
}
else if (6 == k) {
sum = sum + 6;
}
else if (7 == k) {
sum = sum + 7;
}
else if (8 == k) {
sum = sum + 8;
}
else if (9 == k) {
sum = sum + 9;
}
else {
sum = sum + 10;
}
}
}
}
void test_switch_case() {
for (int i = 0;i < LOOP;i++) {
int sum = 0;
for (int k = 0;k < N;k++) {
switch (k) {
case 0:
sum = sum + 1;
break;
case 1:
sum = sum + 2;
break;
case 2:
sum = sum + 2;
break;
case 3:
sum = sum + 3;
break;
case 4:
sum = sum + 4;
break;
case 5:
sum = sum + 5;
break;
case 6:
sum = sum + 6;
break;
case 7:
sum = sum + 7;
break;
case 8:
sum = sum + 8;
break;
case 9:
sum = sum + 9;
break;
default:
sum = sum + 10;
break;
}
}
}
}
int main() {
// test_if_else(); // 0.331s
test_switch_case(); // 0.178s
return 0;
}
标签:case,int,sum,else,break,switch,test From: https://blog.51cto.com/u_15899033/5902965