- 论坛徽章:
- 44
|
本帖最后由 windoze 于 2016-11-02 23:20 编辑
刚才做了一个micro benchmark,代码如下:
- #include <chrono>
- #include <iostream>
- #include <algorithm>
- constexpr size_t len=100000;
- int test_data[len];
- size_t garbage;
- void generate_test_data() {
- for(size_t i=0; i<len; i++) {
- test_data[i]=i;
- }
- }
- int upperBound(void *key,void *data,int data_count,int (*compare)(void *key,void *data,int n))
- {
- int middle,start=0,end=data_count-1,val;
- int result=-1;
- if(!key||!data) return -1;
- while(start <= end) {
- middle = start + ((end-start) >> 1);
- val=compare(key,data,middle);
- if(val>0) {
- if(!middle||compare(key,data,middle - 1) <= 0)
- result=middle;
- end=middle-1;
- } else start=middle+1;
- };
- return result;
- }
- int cmp(void *key, void *data, int n) {
- return ((int *)data)[n]-*((int *)key);
- }
- void test1() {
- // Find the last element smaller than 80000 in test_data
- int key=80000;
- // Make sure this is not optimized;
- garbage+=upperBound(&key,test_data,len,cmp)-1;
- }
- struct cmp_stl {
- bool operator()(int a, int b) const { return a<b; }
- };
- void test2() {
- // Find the last element smaller than 80000 in test_data
- // Make sure this is not optimized;
- garbage+=std::upper_bound(test_data, test_data+len, 80000, cmp_stl())-test_data-1;
- }
- void time_it(size_t repeat, void(*f)()) {
- auto start=std::chrono::system_clock::now();
- for(size_t i=0; i<repeat; i++) {
- f();
- }
- auto end=std::chrono::system_clock::now();
- std::cout << "Duration: " << (end-start).count() << std::endl;
- }
- int main() {
- generate_test_data();
- // Warm up
- for(size_t i=0; i<100; i++) {
- test1();
- test2();
- }
- std::cout << "Test1 ";
- time_it(100000, test1);
- std::cout << "Test2 ";
- time_it(100000, test2);
- }
复制代码
用O3优化:
Test1 Duration: 3038
Test2 Duration: 2581
STL比你的代码快15%
|
|