程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> c++多線程與POSIX多線程性能比較

c++多線程與POSIX多線程性能比較

編輯:C++入門知識

c++多線程與POSIX多線程性能比較


一 代碼結構

二 代碼詳解

1. test.cpp

 

/*************************************************************************
    > File Name: test.cpp
    > Author: wangzhicheng
    > Mail: [email protected] 
    > Created Time: Thu 26 Feb 2015 09:35:49 PM WST
 ************************************************************************/
#include   
#include   
#include   
#include   
#include 
#include 
#include 
#include 
#include 
#include 
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...!
);
			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..!
);
			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
	

	/*www.Bkjia.com
	 * 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


 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved