How do I have different initialization (setup) methods for different tests in JMH? - jmh

I'm writing a JMH test to compare two different implementations. So I have something like:
Counter c1;
Counter c2;
#Setup
public void setup() {
c1 = new Counter1();
c2 = new Counter2();
}
#Benchmark
public int measure_1_c1() {
return measure(c1);
}
#Benchmark
public int measure_2_c2() {
return measure(c2);
}
Each test will run in its own forked JVM. The issue is that it takes a lot of setup in the constructor for each operation (and I have about 20 of then). So what I'd like to do in my #Setup method is to initialize only the one that will be used depending on the test being run in this forked JVM.
Is there a way to do that?

Yes, you need separate #State objects and reference them as needed. For example:
#State
public static class State1 {
int x;
#Setup
void setup() { ... }
}
#State
public static class State2 {
int y;
#Setup
void setup() { ... }
}
#Benchmark
public int measure_1(State1 s1) {
// Only s1 #Setup have run
// use s1.x...
}
#Benchmark
public int measure_2(State2 s2) {
// Only s2 #Setup have run
// use s2.y...
}
#Benchmark
public int measure_3(State1 s1, State2 s2) {
// s1 and s2 #Setups have run
// use s1.x, s2.y...
}

Related

Double LinkList in data structure

When I create a double Linklist By using C(C99), if I add the code: struct DNonde***first**=NULL; on the main function when running Display function the parameter first = NULL. If I remove the additional code: struct DNonde *first = NULL; then structure point: first will normally running as the linklist's first node's address and the Display funtion will also normally running.
However the question is I am using the Create function to create double Linklist after the code:struct DNonde*first=NULL;thus, it will not influence the latter codes, and when I debug the codes it shows me that the double Linklist is created successfully but when in Display function the first = NULL. And why it cause that?
Below is the source code
#include "stdio.h"
#include "stdlib.h"
struct DNonde
{
struct DNonde *preview;
int data;
struct DNonde *next;
}*first=NULL;
void Create(int a[],int length)
{
struct DNonde*tem = NULL;
first =(struct DNonde*)malloc(sizeof(struct DNonde));
first->preview=NULL; first->data=a[0]; first->next=NULL;
struct DNonde *control = first;
for(int i=1;i<length;i++)
{
tem =(struct DNonde*)malloc(sizeof(struct DNonde));
control->next = tem;
tem->preview = control; tem->data = a[i]; tem->next=NULL;
control = tem;
}
}
void Display(struct DNonde*first)
{
do
{
printf("%d ",first->data);
first=first->next;
}while(first != NULL);
}
int main()
{
int a[]={1,3,4,5};
struct DNonde*first=NULL;
Create(a, 4);
Display(first);
}

Storing derived classes in a vector of base class

I have seen several versions of my question, but I still cannot find an answer that works. I have defined a base class called TwoPort and two derived classes called Reflector and Waveguide as follows:
#include <vector>
class TwoPort
{
public:
TwoPort() { yeast = ywest = 0.0; }
~TwoPort() {}
double getyeast() { return yeast; }
double getywest() { return ywest; }
virtual void step(double xeast, double xwest);
protected:
double yeast;
double ywest;
};
class Reflector :
public TwoPort
{
public:
Reflector() { Gamma = 0.0; }
~Reflector() {}
void step(double xeast, double xwest) override;
void setReflection(double G) { Gamma = G; }
private:
double Gamma;
};
class Waveguide :
public TwoPort
{
public:
Waveguide() { oldest = 0; }
~Waveguide() {}
void step(double xeast, double xwest) override;
void setDelay(unsigned int delay);
private:
std::vector<double> eastBuffer, westBuffer;
unsigned int oldest;
};
My goal is to create a vector containing a mixture of Reflectors and Waveguides. Based on the answers to previous questions like mine, I have tried a number of approaches, but so far none have worked. For example:
int main()
{
std::vector<std::unique_ptr<TwoPort>> tpcascade;
tpcascade.emplace_back(new Reflector);
tpcascade.emplace_back(new Waveguide);
tpcascade.emplace_back(new Reflector);
tpcascade[0]->setRefection(0.25);
}
In this case, the compiler does not recognize the setReflection method. So I tried this:
int main()
{
std::vector<std::unique_ptr<TwoPort>> tpcascade;
auto ref = std::make_unique<Reflector>();
ref->setReflection(0.25);
tpcascade.emplace_back(ref);
}
In this case I can set the reflection but I get a lengthy and complex error message about the emplace statement.
Help!
Did some research and tried a variation on the second approach above:
int main()
{
std::vector<std::unique_ptr<TwoPort>> tpcascade;
auto ref = std::make_unique<Reflector>();
ref->setReflection(0.25);
tpcascade.push_back(std::move(ref));
}
Switching to shared_ptr seems to work too, and is a bit cleaner:
int main()
{
std::vector<std::shared_ptr<TwoPort>> tpcascade;
auto ref = std::make_shared<Reflector>();
ref->setReflection(0.25);
tpcascade.push_back(ref);
}
This also seems to work, but seems risky to me:
tpcascade.push_back(std::make_shared<Reflector>());
std::dynamic_pointer_cast<Reflector>(tpcascade[0])->setReflection(0.25);

Calculating the standard deviation of a linkedlist elements

I wanted to calculate the standard deviation of a inked list elements,so I wrote a function to calculate both the average and the sum and then claculate the standard deviation by the formula , but I am getting error " 0xC0000005: Access violation reading location 0x00000000."at the line 46 ,
sd += ((first->info)-average)*((first->info-average);
Why this problem occurs and is there any way to get rid of it ?
My code is as follows :
class Node
{
public:
int info;
Node* next;
int value;
};
class List:public Node
{
Node *first,*last;
public:
List()
{
first=NULL;
last=NULL;
}
void create();
void insert();
void delet();
void display();
void search();
void sum();
void sd();
};
void List::sd()
{
system("cls");
cout<<"The Linked List Operations Program";
cout<<"\n==========================================================="<<endl;
Node *temp=first;
int sd = 0;
int length=0;
while(temp!=NULL)
{
length++;
temp=temp->next;
}
int sum = 0;
while (first != NULL)
{
sum += first->info;
first = first->next;
}
int average;
average = (sum/length);
sd += ((first->info)-average)*((first->info-average);
first=first->next;
cout<<average;
cout<<"The standard diviation is " <<sqrt(sd)/10 ;
cin.get();
cin.get();
}
int main()
{
system("cls");
int m;
List l;
Node *first;
int ch;
l.sd();
return 0 ;
}
void List::create()
{
system("cls");
cout<<"The Linked List Operations Program";
cout<<"\n==========================================================="<<endl;
Node *temp;
temp=new Node;
int n;
cout<<"\nEnter an element to create the first node of the linkedlist:";
cin>>n;
temp->info=n;
temp->next=NULL;
if(first==NULL)
{
first=temp;
last=first;
}
else
{
last->next=temp;
last=temp;
}
}
void List::insert()
{
system("cls");
cout<<"The Linked List Operations Program";
cout<<"\n==========================================================="<<endl;
Node *prev,*cur;
prev=NULL;
cur=first;
int count=1,pos,ch,n;
Node *temp=new Node;
cout<<endl<<"ADDED";
system("cls");
temp->info=rand();
temp->next=NULL;
last->next=temp;
last=temp;
}

Property values are lost (after each loop) when nesting libraries

I created 2 libraries to use in my Arduino code. One is a HwSwitch library, the other is a HwServo library which uses the HwSwitch library.
HwSwitch Library:
HwSwitch::HwSwitch(String switchName, int switchPort, int inputType, int pressedState)
{
Name = switchName;
SwitchPort = switchPort;
_pressedState = pressedState;
_lastCheckMillis = 0;
pinMode(switchPort, inputType);
_lastPinState = digitalRead(SwitchPort);
}
bool HwSwitch::IsPressed()
{
int currentPinState = GetPinState();
return currentPinState == _pressedState;
}
bool HwSwitch::SwitchStateChanged()
{
int currentPinState = GetPinState();
if (_lastPinState != currentPinState)
{
Serial.println("---");
Serial.println("1. Now: " + String(currentPinState) + " - Prev: " + String(_lastPinState));
_lastPinState = currentPinState;
Serial.println("2. Now: " + String(currentPinState) + " - Prev: " + String(_lastPinState));
return true;
}
return false;
}
int HwSwitch::GetPinState()
{
unsigned long ms = millis();
if ((ms - _lastCheckMillis) < 50)
{
return _lastPinState;
}
_lastCheckMillis = ms;
return digitalRead(SwitchPort);
}
HwServo Library:
HwServo::HwServo(int servoPort, int zeroPoint, HwSwitch limitSwitch)
{
_servo.attach(servoPort);
_servo.write(zeroPoint);
ServoPort = servoPort;
ZeroPoint = zeroPoint;
LimitSwitch = limitSwitch;
}
void HwServo::RotateUp()
{
_servo.write(ZeroPoint + UP);
}
void HwServo::RotateDown()
{
if (!LimitSwitch.IsPressed())
{
_servo.write(ZeroPoint + DOWN);
}
}
void HwServo::Stop()
{
_servo.write(ZeroPoint);
}
And this is how I initialized it in the Arduino code:
HwServo HwServos[] = {
HwServo(9, 94, HwSwitch("S1", 14, INPUT_PULLUP, HIGH)),
HwServo(5, 90, HwSwitch("S2", 8, INPUT_PULLUP, HIGH)),
};
void setup() { }
void loop() {
for(int i = 0; i < 2; i++)
{
HwServo hwServo = HwServos[i];
if (hwServo.LimitSwitch.SwitchStateChanged())
{
SendSwitchStateUpdate(hwServo.LimitSwitch);
if (hwServo.LimitSwitch.IsPressed())
{
hwServo.Stop();
}
}
}
}
Now finally to the problem! As you can see in the HwSwitch library I output some data using Serial.println. Here I can see that _lastPinState is successfully updated, but gets reset after every loop. However, when I create a HwSwitch directly and use it, _lastPinState is not reset. In other words, the resetting of the value only seems to occur when the HwSwitch library is used inside the HwServo library.
Appearently this has something to do with the pointers? I am probably initializing my classes incorrectly, but I have no idea how to fix it. Anyone that can help with (and preferably explain) this issue?
I don't have my Arduino on me right now, but I took look and re-wrote your code, added the omitted constructors at my best guess, and got it to compile. There were some things which needed corrected. I'm sure there are other ways, but this is what I did.
For complete code, go here.
First, I created some pointers to objects I'd like to stick around, like so:
HwServo *HwServos[2];
HwSwitch *s1;
HwSwitch *s2;
HwServo *sv1;
HwServo *sv2;
Now each is reserved in memory on the Arduino.
Now, construct the objects in setup():
void setup() {
s1 = new HwSwitch("S1", 14, INPUT_PULLUP, HIGH);
s2 = new HwSwitch("S2", 8, INPUT_PULLUP, HIGH);
sv1 = new HwServo(9, 94, *s1);
sv2 = new HwServo(5, 90, *s2);
//Now, since you're going through an array:
HwServos[0] = sv1;
HwServos[1] = sv2;
}
Use that setup function!!! Maybe not always necessary, or in some cases even recommended, but it's nice to collect things which only need created once there, especially is this case.
Note that new was not used inside the scope of either object, but rather in the scope of the program... So no fancy destructors in your objects are required. Normally, you'd worry about deleting them all before program termination (or whenever best suited), but in Arduino's case, it'll just lose power and kill everything anyway.
You should change your class definitions to this:
class HwSwitch {
public:
String Name;
int SwitchPort;
int _pressedState;
int _lastCheckMillis;
int _lastPinState;
HwSwitch(String, int, int, int);
bool IsPressed();
bool SwitchStateChanged();
int GetPinState();
};
class HwServo {
public:
HwServo();
HwServo(int, int, HwSwitch &);
int ServoPort;
int ZeroPoint;
HwSwitch & LimitSwitch;
void RotateUp();
void RotateDown();
void Stop();
Servo _servo;
};
Note: I made everything public, feel free to move private stuff back to private if you wish.
I changed the constructors to:
HwSwitch::HwSwitch(String switchName, int switchPort, int inputType, int pressedState)
{
Name = switchName;
SwitchPort = switchPort;
_pressedState = pressedState;
_lastCheckMillis = 0;
pinMode(switchPort, inputType);
_lastPinState = digitalRead(SwitchPort);
}
HwServo::HwServo(int servoPort, int zeroPoint, HwSwitch &limitSwitch)
{
_servo.attach(servoPort);
_servo.write(zeroPoint);
ServoPort = servoPort;
ZeroPoint = zeroPoint;
LimitSwitch = limitSwitch;
}
And I modified loop() like so:
void loop() {
// put your main code here, to run repeatedly:
for(int i = 0; i < 2; i++)
{
if (HwServos[i]->LimitSwitch.SwitchStateChanged())
{
SendSwitchStateUpdate(HwServos[i]->LimitSwitch);
if (HwServos[i]->LimitSwitch.IsPressed())
{
HwServos[i]->Stop();
}
}
}
}

How do i get this 2 dimensional array to display as a table?

I need to make a table of seats with varying prices. Heres what i got so far. Im having trouble producing a table.
public class theatSeat {
public static final int rows=9;
public static final int cols=10;
public static void dispBox(int[][] a){
for (int row=0;row<rows;row++){
System.out.print((row+1)+" ");
for (int col=0;col<cols;col++){
System.out.print(a[row][col]+" ");
System.out.println();
}
}
}//Sets the diplayed seating box
public static void getPrice(int[][]a){
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] [] table = new int[rows] [cols];
for(int row=0;row<rows;row++){
for(int col=0;col<cols;col++){
table[row][col]=0;
}
}
dispBox(table);
}}//fin.
In your loop, you're making all the values 0. Did you want something like random value for each? Like this
Random random = new Random();
for(int row=0;row<rows;row++){
for(int col=0;col<cols;col++){
table[row][col]=random.nextInt(50);
}
}
If you're having problems with displaying, try this
public static void dispBox(int[][] a){
for (int row=0;row<rows;row++){
System.out.print((row+1)+" ");
for (int col=0;col<cols;col++){
System.out.print(a[row][col]+" ");
}
System.out.println();
// this needs to go at the end of each line.
// You were putting it at the end of each print
}
}

Resources