Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/126.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
哪种方法更有效? 我正在玩C++,目的是为了更好地编写高效的代码和算法。我试图解决一个非常琐碎的问题,一个整数可以被2整除多少次,我想出了以下方法: int timesTwo1 ( int x ) { long s = clock(); int count = 0; while( x%2 == 0 && (x>>=1) && (++count) && ( (x ^ INT_MAX) & 1 != 0 ) ); long e = clock(); std::cout << "timesTwo1 : " << (e - s) / double(CLOCKS_PER_SEC) * 10e6 << "us\n"; return count; } int timesTwo2 ( int x ) { long s = clock(); int count = 0; while ( x%2 == 0 && (x/=2) && (++count) ); long e = clock(); std::cout << "timesTwo2 : " << (e - s) / double (CLOCKS_PER_SEC) * 10e6 << "us\n"; return count; }_C++ - Fatal编程技术网

哪种方法更有效? 我正在玩C++,目的是为了更好地编写高效的代码和算法。我试图解决一个非常琐碎的问题,一个整数可以被2整除多少次,我想出了以下方法: int timesTwo1 ( int x ) { long s = clock(); int count = 0; while( x%2 == 0 && (x>>=1) && (++count) && ( (x ^ INT_MAX) & 1 != 0 ) ); long e = clock(); std::cout << "timesTwo1 : " << (e - s) / double(CLOCKS_PER_SEC) * 10e6 << "us\n"; return count; } int timesTwo2 ( int x ) { long s = clock(); int count = 0; while ( x%2 == 0 && (x/=2) && (++count) ); long e = clock(); std::cout << "timesTwo2 : " << (e - s) / double (CLOCKS_PER_SEC) * 10e6 << "us\n"; return count; }

哪种方法更有效? 我正在玩C++,目的是为了更好地编写高效的代码和算法。我试图解决一个非常琐碎的问题,一个整数可以被2整除多少次,我想出了以下方法: int timesTwo1 ( int x ) { long s = clock(); int count = 0; while( x%2 == 0 && (x>>=1) && (++count) && ( (x ^ INT_MAX) & 1 != 0 ) ); long e = clock(); std::cout << "timesTwo1 : " << (e - s) / double(CLOCKS_PER_SEC) * 10e6 << "us\n"; return count; } int timesTwo2 ( int x ) { long s = clock(); int count = 0; while ( x%2 == 0 && (x/=2) && (++count) ); long e = clock(); std::cout << "timesTwo2 : " << (e - s) / double (CLOCKS_PER_SEC) * 10e6 << "us\n"; return count; },c++,C++,在我的机器上,ubuntu 14.04LTS 64位intel处理器5i系列的执行时间为10微秒,我看到timesTwo2可读性更强,但哪一个更有效?多亏了不要陷入微观优化的陷阱,这本身就是危险的,因为你失去了性能问题所在的大局。2您开始编写难以阅读因而难以维护的代码。此外,编译器在大多数情况下都可以在这个级别进行优化。而是使用分析来确定问题发生的位置。请不要忘记80/20规则,你实际上是如何测量的?调用一次不会给出太多可靠的基准测试结果。如果您想进一步牺牲可读性,您可以将x%2更改为x&1我认

在我的机器上,ubuntu 14.04LTS 64位intel处理器5i系列的执行时间为10微秒,我看到timesTwo2可读性更强,但哪一个更有效?多亏了

不要陷入微观优化的陷阱,这本身就是危险的,因为你失去了性能问题所在的大局。2您开始编写难以阅读因而难以维护的代码。此外,编译器在大多数情况下都可以在这个级别进行优化。而是使用分析来确定问题发生的位置。请不要忘记80/20规则,你实际上是如何测量的?调用一次不会给出太多可靠的基准测试结果。如果您想进一步牺牲可读性,您可以将x%2更改为x&1我认为x>>=1可能导致未定义的行为,因为x是有符号的整数。除非我记错了……如果您以完全优化的方式查看生成的程序集,我希望它们几乎相同。编译器通常比您更擅长这种窥视孔优化。