关于strtok、strtok_r和strsep的速度问题

之前查strtok和strsep函数时,看到了这么一段话:      

下面的说明摘自于最新的Linux内核2.6.29,说明了strtok()已经不再使用,由速度更快的strsep()代替。

/** linux/lib/string.c** Copyright (C) 1991, 1992 Linus Torvalds*/  

/** stupid library routines.. The optimized versions should generally be found  

* as inline code in   

* These are buggy as well..  

* * Fri Jun 25 1999, Ingo Oeser   

* - Added strsep() which will replace strtok() soon (because strsep() is  

* reentrant and should be faster). Use only strsep() in new code, please.  

** * Sat Feb 09 2002, Jason Thomas ,  

* Matthew Hawkins   

* - Kissed strtok() goodbye

从上面可以看到,strsep的速度应该是优于strtok的,但是今天写了一个简单的测试程序,发现好像并不是这样,程序如下所示:

int main(int argc, char *argv[])
{
	int i = 0;
	vector<string> vect;
	char buf[1024] = "";
	struct timeval tv_old;
	struct timeval tv_new;
	gettimeofday(&tv_old, NULL);
	for (i = 0; i < 1000000; i++)
	{
		strcpy(buf, str_test);
		str_split(buf, ";", vect);
	}
	gettimeofday(&tv_new, NULL);
	printf("spend time : %d\n", (tv_new.tv_sec - tv_old.tv_sec) * 1000000 + (tv_new.tv_usec - tv_old.tv_usec));
	return 0;
}

其中,str_test的定义如下:

char *str_test = "scada;scada1;scada2;scada3;scada4;scada5";

上面的是主函数,其中,str_split是我之前封装的函数,用来将str_test按照“;”分割后放入容器中,其中我用strtok、strtok_r、strsep三个不同的方法实现了str_split,下面是代码:

strtok:

void str_split(char *buf, const char *delimt, vector<string> &vect)
{
	char *p = buf;
	char * temp = strtok(p, delimt);
	while (temp)
	{
		while (*temp == ' ')
		{
			temp++;
		}
		vect.push_back(temp);
		temp = strtok(NULL, delimt);
	}
}

strtok_r:

void str_split(char *buf, const char *delimt, vector<string> &vect)
{
	char *p = buf;
	char *para_tmp;
	char * temp = strtok_r(p, delimt, &para_tmp);
	while (temp)
	{
		while (*temp == ' ')
		{
			temp++;
		}
		vect.push_back(temp);
		temp = strtok_r(NULL, delimt, &para_tmp);
	}
}

strsep:

void str_split(char *buf, const char *delimt, vector<string> &vect)
{
	char *key_point = NULL;
	char *p = buf;
	while (p)
	{
		if (key_point = strsep(&p, delimt))
		{
			while (*key_point == ' ')
			{
				key_point++;
			}
			vect.push_back(key_point);
		}
	}
}

下面是其中一次的测试结果:

strtok:spend time:695471

strtok_r:spend time:1730981

strsep:spend time:1471265

测了好多次,结果都差不多,可以看到,实际上strtok的速度是最快的,但是线程安全版本的strtok_r的速度是慢于strsep的,所以还是strsep可能效果更好一点,毕竟strtok已经不被建议使用了。

猜你喜欢

转载自blog.csdn.net/qu1993/article/details/81357972