c++11多线程与POSIX多线程性能比较

一 代码结构

二 代码详解

1. test.cpp

/*************************************************************************
    > File Name: test.cpp
    > Author: wangzhicheng
    > Mail: 2363702560@qq.com 
    > Created Time: Thu 26 Feb 2015 09:35:49 PM WST
 ************************************************************************/
#include <stdio.h>  
#include <stdlib.h>  
#include <unistd.h>  
#include <time.h>  
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <pthread.h>
#include <iostream>
#include <thread>
using namespace std;
void* fun(void *arg) {
	return NULL;
}
void g() {
}
int main() {
	int i;
	pid_t pid;
	pthread_t tid;
	struct timeval tv1, tv2;
	unsigned long long elapse;
	/*
	 * create processes
	 * */
/*	gettimeofday(&tv1, NULL);
	for(i = 0;i < 1000;i++) {
		pid = fork();
		if(pid < 0) {
			perror("fork error...!\n");
			exit(EXIT_FAILURE);
		}
		else if(!pid) {
			exit(0);
		}
		else {
			wait(NULL);
		}
	}
	gettimeofday(&tv2, NULL);
	elapse = (tv2.tv_sec - tv1.tv_sec) * 1e6 +(tv2.tv_usec - tv1.tv_usec);
	cout << elapse << endl;   // 2.7026s
*/
	/*
	 * create POSIX threads
	 */
	gettimeofday(&tv1, NULL);
	for(i = 0;i < 1000;i++) {
		if(pthread_create(&tid, NULL, fun, NULL)) {
			perror("threads create error..!\n");
			exit(EXIT_FAILURE);
		}
		pthread_join(tid, NULL);
	}
	gettimeofday(&tv2, NULL);
	elapse = (tv2.tv_sec - tv1.tv_sec) * 1e6 +(tv2.tv_usec - tv1.tv_usec);
	cout << elapse << endl;   // 1.591s
	

	/*
	 * create c++11 threads
	 */
/*	gettimeofday(&tv1, NULL);
	for(i = 0;i < 1000;i++) {
		thread mythread(g);
		mythread.join();
	}
	gettimeofday(&tv2, NULL);
	elapse = (tv2.tv_sec - tv1.tv_sec) * 1e6 +(tv2.tv_usec - tv1.tv_usec);
	cout << elapse << endl;   // 1.848s
*/
	return 0;

}

2.  makfile

CC=g++
all:
	$(CC) -std=c++0x -g -o test test.cpp -pthread -lpthread


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值