iCMS

Fork 多进程 模拟并行访问web service获取响应时间差

iCMS http://www.hlike.cn 2019-08-06 20:57 出处:网络 编辑:@iCMS
#include<ros/ros.h> #include<iostream> #include<string> #include<cstring> //名称空间映射表

Fork 多进程 模拟并行访问web service获取响应时间差

Fork 多进程 模拟并行访问web service获取响应时间差

#include <ros/ros.h>

#include <iostream>

#include <string>

#include <cstring>

// 名称空间映射表

#include "k8s_sum/SumServiceImplPortBinding.nsmap"

#include "k8s_sum/soapSumServiceImplPortBindingProxy.h"

//using namespace std;

#include <stdio.h>

#include <iostream>

#include <unistd.h>

#include <fstream>

#include <time.h>

#include <sys/types.h>

#define NUM 1000

#define FORK_NUM 100

//获取当前时间

double getCurrentTime(){

struct timeval tv;

gettimeofday(&tv,NULL);

//return tv.tv_sec*1000+tv.tv_usec/1000;//毫秒

return tv.tv_sec*1000+tv.tv_usec/1000+tv.tv_usec%1000*0.001;//毫秒带小数

}

//计算数组内平均值

double getAvgDiff(double *diffs){

double sum = 0.0;

for(int i=0;i<NUM;i++){

sum +=*(diffs+i);

}

return sum/NUM;

}

//总处理函数

void handle(){

//输出到文件

std::ofstream fout;

int pid = getpid();

std::string fileName="/tmp/rosSumfile_"+std::to_string(pid)+".dat";

fout.open(fileName,std::ios::app);

double first_time;//记录本次最开始时间

double last_time;//记录本次最后一次时间

double avg_diff;//平均响应时间

double diffs[NUM] ={0.0};

for(int i=0;i<NUM;i++){

SumServiceImplPortBindingProxy sumWebservice;

K8S1__getSum sumRequest;

K8S1__getSumResponse res;

int a,b;

//两个1-100的随机数

a= rand() % 100;

b= rand() % 100;

sumRequest.arg0 = a;

sumRequest.arg1 = b;

std::cout<<"a="<<a<<",b="<<b<<std::endl;

time_t tt = time(NULL);//这句返回的只是一个时间戳 精确到秒

//clock_t start_time,end_time; //这个会精确到毫秒

//start_time = clock();

double start_time,end_time;

start_time = getCurrentTime();

if(i==0){

first_time = start_time;//记录第一次时间

}

fout<<"Current timestamp(k8s_sum) request(ms)="<<std::to_string(start_time);

int result = sumWebservice.getSum(&sumRequest,res);

//sleep(2); 暂停2秒

if(SOAP_OK == result)

{

int sum_value = res.return_;

//time_t tt1 = time(NULL);

end_time = getCurrentTime();

if(i+1==NUM){

last_time = end_time;

}

fout<<",response(ms)="<<std::to_string(end_time);

fout<<",the diff(ms)="<<end_time-start_time<<std::endl;

diffs[i]=end_time-start_time;

}else{

fout<<",request is error!"<<std::endl;

}

}

//计算平均响应时间

avg_diff = getAvgDiff(diffs);

fout<<"Count firstTime="<<std::to_string(first_time)<<",lastTime="<<std::to_string(last_time)<<",avgDiff="<<avg_diff<<std::endl;

fout.close();

}

int main(int argc,char **argv)

{

ros::init(argc,argv,"k8s_sum_node");

pid_t pid;

//创建子进程

for(int i=0;i<FORK_NUM;i++){

pid = fork();

//子进程退出循环,不再创建子进程,全部由主进程创建子进程 ,这里是关键所在

if(pid ==0 || pid == -1){

break;

}

}

if(pid == -1){

ROS_INFO("Fail to Fork!");

exit(1);

}

else if(pid == 0){

//子进程处理逻辑

handle();

sleep(5);

exit(0);

}

else{

//主进程处理逻辑

handle();

exit(0);

}

ros::spin();

return 0;

}

View Code

采用了ROS 的编程方式

Web Service 模拟了一个 加法运算,计算求和

0

精彩评论

暂无评论...
验证码 换一张
取 消