add 'likely' optimization test code.
the code currently cannot denote the difference in performance.
This commit is contained in:
parent
9c26dc803d
commit
e5110406ec
85
misc/likely.cpp
Normal file
85
misc/likely.cpp
Normal file
@ -0,0 +1,85 @@
|
|||||||
|
#include <iostream>
|
||||||
|
#include <thread>
|
||||||
|
#include <chrono>
|
||||||
|
#include <sys/time.h>
|
||||||
|
#include <limits.h>
|
||||||
|
|
||||||
|
#define likely(x) __builtin_expect(!!(x), 1)
|
||||||
|
#define unlikely(x) __builtin_expect(!!(x), 0)
|
||||||
|
|
||||||
|
using namespace std;
|
||||||
|
#define SIZE 500000000
|
||||||
|
|
||||||
|
int arr[SIZE];
|
||||||
|
|
||||||
|
void func(int *pval)
|
||||||
|
{
|
||||||
|
double ret = 0;
|
||||||
|
timeval start, end;
|
||||||
|
gettimeofday(&start, nullptr);
|
||||||
|
while (*pval)
|
||||||
|
{
|
||||||
|
if (((*pval) == 256))
|
||||||
|
ret = ret + 1234;
|
||||||
|
else
|
||||||
|
ret = ret + 5678;
|
||||||
|
pval++;
|
||||||
|
}
|
||||||
|
gettimeofday(&end, nullptr);
|
||||||
|
double usec = (end.tv_sec - start.tv_sec) + (double)(end.tv_usec - start.tv_usec) / 1000000;
|
||||||
|
cout << __func__ << " duration: " << usec << ", ret: " << ret << endl;
|
||||||
|
}
|
||||||
|
|
||||||
|
void func_likely(int *pval)
|
||||||
|
{
|
||||||
|
double ret = 0;
|
||||||
|
timeval start, end;
|
||||||
|
gettimeofday(&start, nullptr);
|
||||||
|
while (*pval)
|
||||||
|
{
|
||||||
|
if (likely((*pval) == 256))
|
||||||
|
ret = ret + 1234;
|
||||||
|
else
|
||||||
|
ret = ret + 5678;
|
||||||
|
pval++;
|
||||||
|
}
|
||||||
|
gettimeofday(&end, nullptr);
|
||||||
|
double usec = (end.tv_sec - start.tv_sec) + (double)(end.tv_usec - start.tv_usec) / 1000000;
|
||||||
|
cout << __func__ << " duration: " << usec << ", ret: " << ret << endl;
|
||||||
|
}
|
||||||
|
|
||||||
|
void func_unlikely(int *pval)
|
||||||
|
{
|
||||||
|
double ret = 0;
|
||||||
|
timeval start, end;
|
||||||
|
gettimeofday(&start, nullptr);
|
||||||
|
while (*pval)
|
||||||
|
{
|
||||||
|
if (unlikely((*pval) == 256))
|
||||||
|
ret = ret + 1234;
|
||||||
|
else
|
||||||
|
ret = ret + 5678;
|
||||||
|
pval++;
|
||||||
|
}
|
||||||
|
gettimeofday(&end, nullptr);
|
||||||
|
double usec = (end.tv_sec - start.tv_sec) + (double)(end.tv_usec - start.tv_usec) / 1000000;
|
||||||
|
cout << __func__ << " duration: " << usec << ", ret: " << ret << endl;
|
||||||
|
}
|
||||||
|
|
||||||
|
int main()
|
||||||
|
{
|
||||||
|
for (int i = 0; i < SIZE; i++)
|
||||||
|
{
|
||||||
|
if (i % 1000 == 0)
|
||||||
|
*(arr + i) = 256;
|
||||||
|
else
|
||||||
|
*(arr + i) = 128;
|
||||||
|
}
|
||||||
|
arr[SIZE - 1] = 0;
|
||||||
|
std::thread t1(func, arr);
|
||||||
|
std::thread t2(func_likely, arr);
|
||||||
|
std::thread t3(func_unlikely, arr);
|
||||||
|
t1.join();
|
||||||
|
t2.join();
|
||||||
|
t3.join();
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user