memset对bool型变量赋false比对int型变量赋0快了10倍
fill对bool型变量赋false和对int型变量赋0效率一样
fill对int型变量赋0比memset对int型变量赋0慢了10倍
归结来说,以后要赋变量false的初值时,应该用bool型变量,用memset赋
#include#include #include #include using namespace std;int d[2000000];bool d2[2000000];int has_train[1000][1000][2];bool has_train2[1000][1000][2];int main(){ clock_t start, finish; start = clock(); int k = 1000; while(k--) { memset(d, 0, sizeof(d)); } finish = clock(); printf("%f\n", (double)(finish - start) / CLOCKS_PER_SEC); start = clock(); k = 1000; while(k--) { memset(d2, false, sizeof(d2)); } finish = clock(); printf("%f\n", (double)(finish - start) / CLOCKS_PER_SEC); start = clock(); k = 1000; while(k--) { memset(has_train, 0, sizeof(has_train)); } finish = clock(); printf("%f\n", (double)(finish - start) / CLOCKS_PER_SEC); start = clock(); k = 1000; while(k--) { memset(has_train2, false, sizeof(has_train2)); } finish = clock(); printf("%f\n", (double)(finish - start) / CLOCKS_PER_SEC); start = clock(); k = 1000; while(k--) { fill(d, d+2000000, 0); } finish = clock(); printf("%f\n", (double)(finish - start) / CLOCKS_PER_SEC); start = clock(); k = 1000; while(k--) { fill(d2, d2+2000000, false); } finish = clock(); printf("%f\n", (double)(finish - start) / CLOCKS_PER_SEC); start = clock(); k = 1000; while(k--) { fill(has_train[0][0], has_train[0][0]+2000000, 0); } finish = clock(); printf("%f\n", (double)(finish - start) / CLOCKS_PER_SEC); start = clock(); k = 1000; while(k--) { fill(has_train2[0][0], has_train2[0][0]+2000000, false); } finish = clock(); printf("%f\n", (double)(finish - start) / CLOCKS_PER_SEC); return 0;}
//最后我尝试了直接对int型和bool型数组赋值而不使用memset和fill,发现效率和memset对int 型数组赋值0效率是一样的。