进程线程性能对比—创建和销毁测试

发表于:2015-7-14 11:14

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:lowkey2046    来源:51Testing软件测试网采编

  多进程和多线程信能测试
  创建然后终止进程50000次
  创建进程代码
// fork.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#define NFORKS 50000
void do_nothing()
{
int i;
i= 0;
}
int main(int argc, char *argv[])
{
int pid, i, status;
for (i=0; i<NFORKS; i++) {
/*** error handling ***/
if ((pid = fork()) < 0 ) {
printf ("fork failed with error code= %d\n", pid);
exit(0);
}
/*** this is the child of the fork ***/
else if (pid ==0) {
do_nothing();
exit(0);
}
/*** this is the parent of the fork ***/
else {
waitpid(pid, &status, 0);
}
}
exit(0);
}
  创建线程代码
  创建然后终止线程50000次
// pthread_create.c
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NTHREADS 50000
void *do_nothing(void *null)
{
int i;
i=0;
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
int rc, i;
pthread_t tid;
for (i=0; i<NTHREADS; i++) {
rc = pthread_create(&tid, NULL, do_nothing, NULL);
if (rc) {
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
/* Wait for the thread */
rc = pthread_join(tid, NULL);
if (rc) {
printf("ERROR; return code from pthread_join() is %d\n", rc);
exit(-1);
}
}
pthread_exit(NULL);
}
  编译
  gcc fork.c -o fork -Wall
  gcc pthread_create.c -o pthread_create -Wall
  执行
  测试环境信息
  $ cat /proc/cpuinfo | grep name | uniq
  model name: AMD Athlon(tm) 64 X2 Dual Core Processor 5200+
  $ uname -a
  Linux Mint 3.16.0-36-generic #48~14.04.1-Ubuntu SMP Wed Apr 15 13:11:28 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
  测试进程创建然后销毁的时间
  $ time ./fork
  real0m12.539s
  user0m0.124s
  sys0m13.070s
  测试线程创建然后销毁的时间
  $ time ./pthread_create
  real0m1.995s
  user0m0.503s
  sys0m1.821s
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号