69,369
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <ctime>
#include <string.h>
#include <pthread.h>
#include <sys/time.h>
using namespace std;
long long int toddiff(struct timeval *tod1, struct timeval *tod2);
void Fun_1()
{
struct timeval tod1, tod2;
gettimeofday(&tod1, NULL);
/* do something:1 */
sleep(5);
gettimeofday(&tod2, NULL);
cout<<"function-1 run time: "<< toddiff(&tod2, &tod1) / 1000000.0<<endl;
}
void Fun_2()
{
struct timeval tod1, tod2;
gettimeofday(&tod1, NULL);
/* do something:2 */
sleep(5);
gettimeofday(&tod2, NULL);
cout<<"function-2 run time: "<< toddiff(&tod2, &tod1) / 1000000.0<<endl;
}
void *threadFun_1(void*)
{
struct timeval tod1, tod2;
gettimeofday(&tod1, NULL);
/* do something:1 */
sleep(5);
gettimeofday(&tod2, NULL);
cout<<"thread function-1 run time: "<< toddiff(&tod2, &tod1) / 1000000.0<<endl;
}
void *threadFun_2(void*)
{
struct timeval tod1, tod2;
gettimeofday(&tod1, NULL);
/* do something:2 */
sleep(5);
gettimeofday(&tod2, NULL);
cout<<"thread function-2 run time: "<< toddiff(&tod2, &tod1) / 1000000.0<<endl;
}
/*使用多线程*/
int main()
{
struct timeval tod1, tod2;
gettimeofday(&tod1, NULL);
pthread_t pthread_id_1;
pthread_t pthread_id_2;
pthread_create(&pthread_id_1, NULL, threadFun_1, NULL);
pthread_create(&pthread_id_2, NULL, threadFun_2, NULL);
pthread_join(pthread_id_1, NULL);
pthread_join(pthread_id_2, NULL);
gettimeofday(&tod2, NULL);
cout<<"total times in mulit-thread: "<< toddiff(&tod2, &tod1) / 1000000.0<<endl;
gettimeofday(&tod1, NULL);
Fun_1();
Fun_2();
gettimeofday(&tod2, NULL);
cout<<"total times without mulit-thread: "<< toddiff(&tod2, &tod1) / 1000000.0<<endl;
return 0;
}
long long int toddiff(struct timeval *tod1, struct timeval *tod2)
{
long long t1, t2;
t1 = tod1->tv_sec * 1000000 + tod1->tv_usec;
t2 = tod2->tv_sec * 1000000 + tod2->tv_usec;
return t1 - t2;
}