测试原装libco的asm版 与 libco的ucontext版性能, 同一个机器、同一份代码, 连接不同的libco实现库。 asm版比ucontext快6倍左右。
但是有网友说:
但是1秒切换100万次的应用不多,更多消耗在共享栈拷贝
更多消耗在设置高低电平
libco这种只能是半双工一应一答式, 用udp, 短连接tcp, 或者长连接tcp半双工模式。
长连接的全双工不行, fastrpc底层的协程库是长连接全双工模式。
半双工时, 多开连接数可以提高性能,但也不是越多越好。
#include "co_routine.h"
#include <sys/time.h>#include <stdio.h>
struct Ctx
{
stCoRoutine_t *pCo;
};
int cocount = 2;
int testcount = 1000000;
Ctx *arrayTask = NULL;
int testi = 0;
#define LOGD(x, ...) (x, ##__VA_ARGS__)
#define LOGI(x, ...) printf(x, ##__VA_ARGS__)
void *func1(void *p)
{
co_enable_hook_sys();
while(1)
{
LOGD("func1 %d start\n", testi);
co_yield_ct();
LOGD("func1 %d end\n", testi);
if(testi == testcount) break;
}
LOGD("func1 end...\n");
}
void *func0(void *p)
{
timeval beg,end;
co_enable_hook_sys();
LOGD("func0 poll start\n");
poll(0,0,1000);
LOGD("func0 poll end\n");
gettimeofday(&beg, NULL);
for(; testi < testcount; testi++)
{
LOGD("func0 %d start\n", testi);
co_resume(arrayTask[1].pCo);
LOGD("func0 %d end\n", testi);
}
co_resume(arrayTask[1].pCo);
gettimeofday(&end, NULL);
LOGI("switch %d times, cost: %d(us)\n", testcount, 1000000*(end.tv_sec-beg.tv_sec) + end.tv_usec-beg.tv_usec);
LOGD("func0 end...\n");
}
void run()
{
arrayTask = new Ctx[cocount];
// co_enable_hook_sys();
co_create(&arrayTask[0].pCo, NULL, func0, &arrayTask[0]);
co_resume(arrayTask[0].pCo);
co_create(&arrayTask[1].pCo, NULL, func1, &arrayTask[1]);
co_resume(arrayTask[1].pCo);
co_eventloop(co_get_epoll_ct(), 0, 0);
LOGD("end of run...\n");
}
int main(int, char *[])
{
run();
return 0;
}
本文通过测试libco的asm版本与ucontext版本在相同条件下的性能差异,发现asm版本速度更快。同时讨论了不同场景下协程的使用限制及优化方案。
797

被折叠的 条评论
为什么被折叠?



