如果你还不熟悉 C++,你应该会惊奇 C++ 在某些时候速度比 C 更快些。特别是当代码比较简短时,因为 C++ 的强项 —— 内联(inlineing) 和模板化。
下面的代码对 C 和 C++ 的排序功能进行比较:#include <iostream> #include <algorithm> #include <vector> #include "stop_watch.inl" // see https://gist.github.com/2057981 #ifndef COUNT #define COUNT 100000000 #endif int compare_int(const void* p1, const void* p2) { int i1 = *(int*)p1; int i2 = *(int*)p2; return i1 < i2 ? -1 : i1 > i2 ? 1 : 0; } int main() { srand(12345); int* data1 = new int[COUNT]; int* data2 = new int[COUNT]; for(int i=0; i<COUNT; i++) { data1[i] = data2[i] = ((rand() << 16) | rand()); } { StopWatch stopWatch("std::sort: "); std::sort(data1, data1+COUNT); } { StopWatch stopWatch("qsort: "); qsort(data2, COUNT, sizeof(int), compare_int); } return 0; }
下面结果是在 Macbook Air 上通过 (gcc -DCOUNT=100000 -O3 -Wall sort.cpp -lstdc++) 命令进行编译后的运行测试结果:
count c++ c c/c++ ratio 30000 1769 4949 2.80 100000 6604 17665 2.67 300000 22721 59713 2.63 1000000 79107 231982 2.93 3000000 266550 711608 2.67 10000000 920159 2530939 2.75 30000000 2909369 8259053 2.84 100000000 10016849 28173682 2.81
从上表中可看出,C++ 的速度是 C 的 3 倍,怎么可能呢?
这是 C++ 的 inlining 技术导致的,而 C 语言还需要通过函数指针,这点消耗导致 C 语言的排序在性能上比 C++ 慢。
有趣的是很多人认为 C++ 也会通过指针来调用一个函数。
我的经验:要达到最佳的性能应该尽可能采用如下三个方法:
- 限制分支
- 优化第二级内存缓存
- 考虑 C++ templating
2KB项目(www.2kb.com,源码交易平台),提供担保交易、源码交易、虚拟商品、在家创业、在线创业、任务交易、网站设计、软件设计、网络兼职、站长交易、域名交易、链接买卖、网站交易、广告买卖、站长培训、建站美工等服务