锁
未加锁
int MAX_CNT = 1000 * 10000;
bool run = true;
int gTestN = 0;
TIME_COST([&](){
while (run)
{
gTestN++;
if (gTestN > MAX_CNT)
{
run = false;
}
}
})
// 23 ms
单线程加锁
int MAX_CNT = 1000 * 10000;
bool run = true;
int gTestN = 0;
mutex m ;
TIME_COST([&]()
{
while (run)
{
m.lock();
gTestN++;
if (gTestN > MAX_CNT)
{
run = false;
}
m.unlock();
}
})
// 187ms <---> 100 0000
// 187 000 μs <---> 100 0000
// 187 000 000 ns <---> 100 0000
// 187 ns <---> 1
多线程加锁
int MAX_CNT = 1000 * 10000;
bool run = true;
int gTestN = 0;
thread th1 ([&]()
{
TIME_COST([&]()
{
while (run)
{
m.lock();
gTestN++;
if (gTestN > MAX_CNT)
{
run = false;
}
m.unlock();
}
})
});
thread th2 ([&]()
{
TIME_COST([&]()
{
while (run)
{
m.lock();
gTestN++;
if (gTestN > MAX_CNT)
{
run = false;
}
m.unlock();
}
})
});
th1.join();
th2.join();
//595ms
//595ms
time(nullptr)
bool run = true;
int cnt = 3*10000*10000;
int count = 0;
TIME_COST([&]()
{
while (run)
{
if (count > cnt)
{
run = false;
}
count++;
int x = time(nullptr);
}
})
// 1279 ms <-> 3 0000 0000
// 1279 000 000 ns <-> 3 0000 0000
// 4 ns <-> 1
1.介绍:
很多应用(数据库)频繁执行gettimeofday或是其它类似的函数调用,优化这此函数可以提升性能。
Virtual Dynamic Shared Object(VDSO),是一个允许应用在用户空间执行一些kernel活动(不需要通过系统调用),VDSO可以加速gettimofday的执行
2.原理:
VDSO使用自己的getimeofday的定义覆盖glibc的定义(需要通过系统调用访问内核),从而避免了系统调用。
glibc运行库里有VDSO的实现。VDSO复制了一些内核代码(gettimeofday需要的)。rehat5.5允许gettimeofday完全在用户空间执行,不执行系统调用。
3.VDSO boot参数值:
0 提供精确的时间间隔(微秒),但是会产生大量负载(调用系统调用)
1 稍微有点不精确,但仍是微秒级,负载小。
2 最不精确,毫秒级,负载最小
4.使gettimeofday with VDSO 生效
默认VDSO是打开的,如果没有打开,可以通过下面这个方式打开:
echo 1 > /proc/sys/kernel/vsyscall64
5.补充
这个gettimeofday的优化只在64位架构上有(AMD64,Intel64),在x86上没 有
Currently the gettimeofday speed up is implemented only for 64 bit architectures (AMD64 and Intel 64) and is not available