What does Intel PIN instruction count depend on and why it varies between executions? - intel-pin

I would like to get instruction count for bubblesort algorithm using Intel PIN. I thought that maybe I could analyse how instruction count increases, when there is more data to sort. But the result varies between executions for the same set of data.
For example few outputs: 1662097, 1811453, 1832990, 1745621
It varies quite a lot. Why isn't it the same? Is there a way to achieve it? How am I supposed to get any useful information from that? There is no way of telling how increase of data set influenced number of instructions, when it isn't even stable for the same execution.
Pintool code (copy-pasted from Pin User Guide):
#include <iostream>
#include <fstream>
#include "pin.H"
ofstream OutFile;
// The running count of instructions is kept here
// make it static to help the compiler optimize docount
static UINT64 icount = 0;
// This function is called before every instruction is executed
VOID docount() { icount++; }
// Pin calls this function every time a new instruction is encountered
VOID Instruction(INS ins, VOID *v)
{
// Insert a call to docount before every instruction, no arguments are passed
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)docount, IARG_END);
}
KNOB<string> KnobOutputFile(KNOB_MODE_WRITEONCE, "pintool",
"o", "inscount.out", "specify output file name");
// This function is called when the application exits
VOID Fini(INT32 code, VOID *v)
{
// Write to a file since cout and cerr maybe closed by the application
OutFile.setf(ios::showbase);
OutFile << "Count " << icount << endl;
OutFile.close();
}
/* ===================================================================== */
/* Print Help Message */
/* ===================================================================== */
INT32 Usage()
{
cerr << "This tool counts the number of dynamic instructions executed" << endl;
cerr << endl << KNOB_BASE::StringKnobSummary() << endl;
return -1;
}
/* ===================================================================== */
/* Main */
/* ===================================================================== */
/* argc, argv are the entire command line: pin -t <toolname> -- ... */
/* ===================================================================== */
int main(int argc, char * argv[])
{
// Initialize pin
if (PIN_Init(argc, argv)) return Usage();
OutFile.open(KnobOutputFile.Value().c_str());
// Register Instruction to be called to instrument instructions
INS_AddInstrumentFunction(Instruction, 0);
// Register Fini to be called when the application exits
PIN_AddFiniFunction(Fini, 0);
// Start the program, never returns
PIN_StartProgram();
return 0;
}
Bubblesort implementation (nothing extraordinary, intentionally O(n^2)):
void bubblesort(int table[], int size) {
int i, j, temp;
for (i = 0; i < size - 1; i++)
{
for (j = 0; j < size - 1 - i; j++)
{
if (table[j] > table[j + 1])
{
temp = table[j + 1];
table[j + 1] = table[j];
table[j] = temp;
}
}
}
}

Related

How to make animation in *.gif run only once in Qt? [duplicate]

I'm using QMovie and gif to create explosion after collision. The problem is that my gif is looping over and over, I've checked loopcount status and it returns -1 (infinite). How to display my gif just one time?
#include "Bullet.h"
#include <QTimer>
#include <QGraphicsScene>
#include <QList>
#include "Enemy.h"
#include "Game.h"
#include <typeinfo>
#include "levels.h"
extern Game * game; // there is an external global object called game
int Bullet::killed = 0;
int Bullet::missed = 0;
double Bullet::accurancy = 0;
Bullet::Bullet(QGraphicsItem *parent): QGraphicsPixmapItem(parent){
// draw graphics
setPixmap(QPixmap(":/images/res/images/bullets/bullet.png"));
missed++; // increse missed when bullet is created
movie = new QMovie(":/images/res/images/effects/explosion/64x48.gif");
processLabel = new QLabel;
processLabel->setMovie(movie);
// make/connect a timer to move() the bullet every so often
QTimer * timer = new QTimer(this);
connect(timer,SIGNAL(timeout()),this,SLOT(move()));
// start the timer
timer->start(2);
}
void Bullet::move(){
// get a list of all the items currently colliding with this bullet
QList<QGraphicsItem *> colliding_items = collidingItems();
// if one of the colliding items is an Enemy, destroy both the bullet and the enemy
for (int i = 0, n = colliding_items.size(); i < n; ++i){
if (typeid(*(colliding_items[i])) == typeid(Enemy)){
// increase the score
game->score->increase();
//play explosion animation
movie->start();
movie->setSpeed(180);
processLabel->setAttribute(Qt::WA_NoSystemBackground);
processLabel->setGeometry(QRect(x()-15,y()-15,64,48));
scene()->addWidget(processLabel);
qDebug() << movie->loopCount();
//connect(movie,SIGNAL(finished()),movie,SLOT(stop()));
// remove them from the scene (still on the heap)
scene()->removeItem(colliding_items[i]);
scene()->removeItem(this);
// delete them from the heap to save memory
delete colliding_items[i];
delete this;
killed++;
missed--; // decrese missed if bullet colide with enemy
if((killed+1) % 9 == 0)
{
game->level->Levels::incrementLevels();
game->score->Score::addToSum(); /// TODO
}
//qDebug() << "Already killed: " << killed;
//qDebug() << "Already missed: " << missed;
// return (all code below refers to a non existint bullet)
return;
}
}
// if there was no collision with an Enemy, move the bullet forward
setPos(x(),y()-1);
// if the bullet is off the screen, destroy it
if (pos().y() < 0){
scene()->removeItem(this);
delete this;
}
}
I had the same question and didn't find anything, so here's my solution:
connect the signal "frameChanged(int)" to:
void Bullet::frameChanged_Handler(int frameNumber) {
if(frameNumber == (movie->frameCount()-1)) {
movie->stop();
}
}
If you want to run X times the loop you just have to add a static counter to know how many times you've passed the last frame:
void Bullet::frameChanged_Handler(int frameNumber) {
static int loopCount = 0;
if(frameNumber == (movie->frameCount()-1)) {
loopCount++;
if(loopCount >= MAX_LOOP_TIMES)
movie->stop();
}
}
and of course, connect with this:
connect(movie, SIGNAL(frameChanged(int)), this, SLOT(frameChanged_Handler(int)));
That's it... Hope it can help you.

How to use char* with SD library with Arduino?

I am writing a data logger and would like to keep the files limited to a specific number of entries. I am trying to write this bit of code in the setup, so that when the Arduino powers on, it will write to a new file just to keep things simple. However, when I try to open the file I can't, although I am not sure why. Can anyone offer any explanation?
char *fileName; //global name
File logFile; //global file
//everything else is in setup()
char * topPart = "/Data/Data"; //first part of every file
char * lowerPart = ".txt"; // jus the extention
char * itter; //used to hold the char of i later
fileName = "/Data/Data.txt"; //start with the first file possible.
for(int i=0; i<=100;i++) {
if(!SD.exists(fileName)) {
Serial.print("opening file: ");
Serial.print(fileName);
logFile = SD.open(fileName, FILE_WRITE);
if(logFile) {
logFile.println("I made it");
Serial.println("in the file");
}
if(!logFile) {
Serial.println("somthing bad");
}
break;
} else {
itter = (char *)(i+48);
strcpy(fileName,topPart);
strcpy(fileName,itter);
strcpy(fileName,lowerPart);
Serial.println(i);
}
}
Lots of problems.
the construction of itter is wrong.
strcpy doesn't append just cpy.
Here is a code example to build your filename. This a basic C program. Remove the #include and main for Arduino, this allows to test on your computer whether the program is ok.
#include <string.h>
#define TOPPART "/Data/Data"
#define LOWERPART ".txt"
int main(void) {
char buf[64];
snprintf(buf, sizeof(buf), "%s%s", TOPPART, LOWERPART);
for (int i = 0; i < 100; i++) {
/* here your stuff to check if the filename froml buf exists*/
snprintf(buf, sizeof(buf), "%s%d%s", TOPPART, i, LOWERPART);
}
return 0;
}

Creating multiple child processes with a single pipe

I need to create three child processes, each of which reads a string from the command line arguments and writes the string to a single pipe. The parent would then read the strings from the pipe and display all three of them on the screen. I tried doing it for two processes to test and it is printing one of the strings twice as opposed to both of them.
#include <stdio.h>
#include <unistd.h>
int main (int argc, char *argv[]) {
char *character1 = argv[1];
char *character2 = argv[2];
char inbuf[100]; //creating an array with a max size of 100
int p[2]; // Pipe descriptor array
pid_t pid1; // defining pid1 of type pid_t
pid_t pid2; // defining pid2 of type pid_t
if (pipe(p) == -1) {
fprintf(stderr, "Pipe Failed"); // pipe fail
}
pid1 = fork(); // fork
if (pid1 < 0) {
fprintf(stderr, "Fork Failed"); // fork fail
}
else if (pid1 == 0){ // if child process 1
close(p[0]); // close the read end
write(p[1], character1, sizeof(&inbuf[0])); // write character 1 to the pipe
}
else { // if parent, create a second child process, child process 2
pid2 = fork();
if (pid2 < 0) {
fprintf(stderr, "Fork Failed"); // fork fail
}
if (pid2 = 0) { // if child process 2
close(p[0]); // close the read end
write(p[1], character2, sizeof(&inbuf[0])); // write character 2 to the pipe
}
else { // if parent process
close(p[1]); // close the write end
read(p[0], inbuf, sizeof(&inbuf[0])); // Read the pipe that both children write to
printf("%s\n", inbuf); // print
read(p[0], inbuf, sizeof(&inbuf[0])); // Read the pipe that both children write to
printf("%s\n", inbuf); // print
}
}
}
Your code doesn't keep looping until there's no more data to read. It does a single read. It also doesn't check the value returned by read(), but it should.
I've abstracted the fork() and write() (and error check) code into a function. This seems to work:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
static void child(int fd, const char *string)
{
pid_t pid = fork();
int len = strlen(string);
if (pid < 0)
{
fprintf(stderr, "%.5d: failed to fork (%d: %s)\n",
(int)getpid(), errno, strerror(errno));
exit(1);
}
else if (pid > 0)
return;
else if (write(fd, string, len) != len)
{
fprintf(stderr, "%.5d: failed to write on pipe %d (%d: %s)\n",
(int)getpid(), fd, errno, strerror(errno));
exit(1);
}
else
exit(0);
}
int main (int argc, char *argv[])
{
char inbuf[100]; //creating an array with a max size of 100
int p[2]; // Pipe descriptor array
if (argc != 4)
{
fprintf(stderr, "Usage: %s str1 str2 str3\n", argv[0]);
return 1;
}
if (pipe(p) == -1)
{
fprintf(stderr, "Pipe Failed"); // pipe fail
return 1;
}
for (int i = 0; i < 3; i++)
child(p[1], argv[i+1]);
int nbytes;
close(p[1]); // close the write end
while ((nbytes = read(p[0], inbuf, sizeof(inbuf))) > 0)
printf("%.*s\n", nbytes, inbuf); // print
return 0;
}
I ran the command multiple times, each time using the command line:
./p3 'message 1' 'the second message' 'a third message for the third process'
On one run, the output was:
the second messagemessage 1
a third message for the third process
On another, I got:
the second messagemessage 1a third message for the third process
And on another, I got:
message 1
the second messagea third message for the third process
(This is on a MacBook Pro with Intel Core i7, running Mac OS X 10.8.3, and using GCC 4.7.1.)

error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'Car' (or there is no acceptable conversion)

Queue class
#ifndef Queue_H
#define Queue_H
#include "Car.h"
#include <iostream>
#include <string>
using namespace std;
const int Q_MAX_SIZE = 20;
class Queue {
private:
int size; // size of the queue
Car carQueue[Q_MAX_SIZE];
int front, rear;
public:
Queue();
~Queue();
bool isEmpty();
bool isFull();
void enqueue(Car c);
void dequeue(); // just dequeue the last car in the queue
void dequeue(Car c); // if a certain car wants to go out of the queue midway.
// Condition: Car is not in washing. Meaning is not the 1st item in the queue
void dequeue(int index); // same as the previous comment
Car getFront();
void getCarQueue(Queue);
int length();
Car get(int);
};
Queue::Queue() {
size = 0;
front = 0;
rear = Q_MAX_SIZE -1;
}
Queue::~Queue() {
while(!isEmpty()) {
dequeue();
}
}
void Queue::enqueue(Car c) {
if (!isFull()) {
rear = (rear + 1) % Q_MAX_SIZE; // circular array
carQueue[rear] = c;
size++;
} else {
cout << "Queue is currently full.\n";
}
}
void Queue::dequeue() {
}
void Queue::dequeue(int index) {
if(!isEmpty()) {
front = (front + 1) % Q_MAX_SIZE;
if(front != index) {
carQueue[index-1] = carQueue[index];
rear--;
size--;
} else {
cout << "Not allowed to dequeue the first car in the queue.\n";
}
} else {
cout << "There are no cars to dequeue.\n";
}
}
bool Queue::isEmpty() {
return size == 0;
}
bool Queue::isFull() {
return (size == Q_MAX_SIZE);
}
Car Queue::getFront() {
return carQueue[front];
}
int Queue::length() {
return size;
}
Car Queue::get(int index) {
return carQueue[index-1];
}
void Queue::getCarQueue(Queue q) {
for(int i = 0; i< q.length(); i++)
cout << q.get(i) << endl; // Error here
}
#endif
error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'Car' (or there is no acceptable conversion)
I get this error which is kind of odd. so is there anything wrong? Thanks!
cout has no idea how to process a car object; it has never seen a car object and doesn't know how you output a car as text. cout can only process types it knows about, string, char, int, etc. The specific error is because there is version of operator << that takes an ostream and a car.
There are two options:
Creation an overload for operator<< that takes an ostream and a car. That will show cout how to output a car. This isn't usually done becuase there is usually more than one way your would want to display a car.
Write the output statement so that it manually prints out car properties like
cout << c.getMake() << " " << c.getModel()

Stack-recursion program problems

I am a novice C++ coder and obviously not very good at it. I am having an immense amount of trouble with this program.
I am getting syntax errors on my opening and closing parenthesis on my functions, syntax errors on my "<" in my header cpp file, and errors that I'm missing parenthesis.
My first stack is not recognized (main driver file) and in my StackType.cpp file - original is an "undeclared identifier".
Lastly, the left of Push must have class/struct/union - in my for loop when filling the first stack with the rings.
I apologize for all of these issues in advance. Any help you could give me would be greatly appreciated!
Thank you.
======================Stack Header================================
// File: StackType.h
// Stack template class definition.
// Dynamic array implementation
#ifndef StackType
#define StackType
template <class ItemType>
class StackType
{
private:
int ItemType;
ItemType *myStack; // pointer to dynamic array
int _top, _maxSize; // using underscores to remind that it's private
public:
StackType(int numRings = 50); // Constructor
StackType (const StackType<ItemType>&); // Copy Constructor
// Member Functions
void Push(ItemType); // Push
void Pop(ItemType &); // Pop
void stackTop(ItemType &) const; // retrieve top
bool stackIsEmpty() const; // Test for Empty stack
bool stackIsFull() const; // Test for Full stack
~StackType(); // Destructor
};
#endif
=====================Stack cpp file==================================
#include "StackType.h"
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
// Constructor with argument, size is numRings, limit is 50 (set in .h header)
template <class ItemType>
StackType<ItemType>::StackType()
{
_maxSize = numRings;
_top = -1;
}
// Copy Constructor
template <class ItemType>
StackType<ItemType>::StackType(const StackType<ItemType>& original :
_maxSize(original._maxSize), top(original._top)
{
myStack = new ItemType[_maxSize];
for (int i = 0; i <= top; i++) myStack[i] = original.myStack[i];
}
// Destructor
template <class ItemType>
StackType<ItemType>::~StackType()
{
delete [] myStack;
}
// Push
template <class ItemType>
void StackType<ItemType>::Push(StackType<ItemType> ringVal)
{
if(stackIsFull()) cout << "\t There is not enough available memory = the stack is
full!" << endl;
else myStack[++_top] = ringVal;
}
// Pop
template <class ItemType>
void StackType<ItemType>::Pop(StackType<ItemType> &ringVal)
{
if(stackIsEmpty()) cout << "\t The stack is empty!" << endl;
else ringVal = myStack[_top--];
}
// Retrieve stack top without removing it
template <class ItemType>
void StackType<ItemType>::stackTop(StackType<ItemType> &ringVal) const
{
if(stackIsEmpty()) cout << "The stack is empty!";
else ringVal = myStack[_top];
}
// Test for Empty stack
template <class ItemType>
bool StackType<ItemType>::stackIsEmpty() const
{
return (_top < 0);
}
// Test for Full stack
template <class ItemType>
bool StackType<class ItemType>::stackIsFull() const
{
return (_top >= (_maxSize - 1));
}
// end StackType.cpp
=========================Main Driver file=======================================
#include "StackType.h"
#ifdef _DEBUG
#include "StackType.cpp"
#endif // _DEBUG
#include <stack>
#include "StdAfx.h"
#include <iostream>
using namespace std;
// Global Variable - Counter to display the number of moves.
int count = 0;
class StackType;
// Functions Prototypes
void MoveRings(StackType<ItemType>&, StackType<ItemType>&);
// Function to move the rings
void Pegs(int D,StackType<ItemType>& b,StackType<ItemType>& e, StackType<ItemType>& h);
// This is a recursive function.
void Display (int, StackType <ItemType>& , StackType<ItemType>&, StackType<ItemType>&);
// Function to display the pegs
// Main - Driver File
int main()
{
// create 3 empty stacks
StackType<ItemType> FirstPeg; // Receiving an error that this is not identified
StackType<ItemType> EndPeg;
StackType<ItemType> HelperPeg;
// Number of rings.
int numRings;
cout << "\n\t *********** Rings to Pegs (Towers of Hanoi) ***********\n" << endl;
cout << "\t Please Enter the number of rings you want to play with: ";
// Input number of rings
cin >> numRings;
cout << endl;
while(numRings < 0 || isalpha(numRings)) // To make sure that the user did not
// enter an invalid number
{
cout << " Your entry is invalid. Please use only integers. Please re-
enter: ";
cin >> numRings;
cout << endl;
}
for(int i = 1; i <= numRings; i++)
// Fill the first peg with the number of rings.
{
FirstPeg.Push(i);
}
Pegs(int, StackType<ItemType>&, StackType<ItemType>&, StackType<ItemType>&);
// To call the recursive function that will move the rings
Display (int, StackType<ItemType>&, StackType<ItemType>&, StackType<ItemType>&);
// To call the display function
cin.clear();
cin.ignore('\n');
cin.get();
return 0;
}
// This function will move an ring from first peg to the second peg
void MoveRings(StackType<ItemType>& beg, StackType<ItemType>& theEnd) //End
{
int r; // disk will be removed from one stack and added to the other
beg.Pop(r);//pop from source
theEnd.Push(r);//and move to target
}
// This function displays the moves
void Display(int R, StackType<ItemType>& toBegin , StackType<ItemType>& toEnd,
StackType<ItemType>& toHelp)
{
StackType<int> B;// create temporarily first stack
StackType<int> E;// create temporarily End(End) stack
StackType<int> H;// create temporarily helper stack
for(int i = 1; i <= R; i++)
{
toBegin.Pop(i);//moves the ring from source
B.Push(i);//to the temporarily stack to display it
cout << "Beginning Peg:" << &B << endl;
toEnd.Pop(i);//moves the ring from source
E.Push(i);//to the temporarily stack to display it
cout << " End(Final) Peg: " << &E << endl;
toHelp.Pop(i);//moves the ring from source
H.Push(i);//to the temporarily stack to display it
cout << " Helper Peg:" << &H << endl;
}
}
//-------------------------------------------------------------------
void Pegs(int D,StackType<ItemType>& b,StackType<ItemType>& e,StackType<ItemType>& h)
// This is a recursive function.
{
if (D == 0) // The base
{
return 1;
}
else if(D == 1) // If there is only one ring, move this ring from the
// first peg to the end(final) peg
{
MoveRings(b, e); // moves the ring from the first to the end(final) peg
cout<<" Really? You have entered one ring..." << endl;
cout<<" It moves directly from the first peg to the End peg." << endl;
count++; // increment the number of moves
cout << "There has been " << count << " move. "<< endl;// display the
// number of moves
Display (D, b, e, h);
}
else if (D > 1) // a recursive function in order to move the rings
{
Pegs(D - 1, b, e, h); // to move N-1 rings from the first peg to the
// end(final) peg by using the helper peg
MoveRings(b, e);// to move the last ring to the end(final) peg
count++; // increment the number of steps before displaying
cout << "There has been " << count << " moves. "<< endl;
Pegs(D - 1, b, e, h);
// to move N-1 rings from the helper peg to the end(final) peg with the help of
// first peg
//Display ( D(rings), First Peg, End(Final) Peg, Helper Peg );
}
}
One problem that I can see immediately is that your header file defines StackType to prevent double inclusion, which is also used as a class name. After #define StackType, it ends up being a macro that expands to nothing, so your code looks like class { ... }.
You should use a symbol to prevent double inclusion that isn't used for anything else. The typical thing to use is STACKTYPE_H for a file called StackType.h.
Once you've fixed this, some other problems you're experiencing might go away. Please come back with an update if you're having more problems, and post the exact compiler errors if you do.

Resources