Logging execution time with cppunit - cppunit

I am doing unit testing with cppunit library. I need to log the execution time for each tests. Is there any way to log the execution time in the XML file? Can someone point me to some examples? My code is below. I want the execution time in the xml file results_cppunit.xml
int main(int argc, char** argv)
{
TestResult result;
TestResultCollector resultCollector;
result.addListener(&resultCollector);
TextUi::TestRunner runner;
runner.addTest(TestFactoryRegistry::getRegistry().makeTest());
runner.run(result);
ofstream xmlFileOut("results_cppunit.xml");
XmlOutputter xmlOut(&resultCollector, xmlFileOut);
xmlOut.write();
return resultCollector.wasSuccessful() ? 0 : 1;
}

CppUnit::TestResult has an addListener method. You can add a subclass of CppUnit::TestListener that just logs the time of the test by overwriting startTest and endTest.
You can see an example for that in the Libreoffice source code.

I managed to do it using both TestListener and XmlOutputterHook. TestListener to log the execution time and XmlOutputterHook to insert it into xml.

Related

Sending SIGINT to QProcess

I want to send SIGINT to a program started using QProcess.
I am working on ubuntu.
Source code of my process looks like this:
#include <iostream>
#include <csignal>
#include <stdlib.h>
#include <unistd.h>
void int_handle(int sig)
{
std::cout<<"Received SIGINT\n";
exit(0);
}
int main()
{
std::cout<<"Main called\n";
signal(SIGINT, int_handle);
while(1)
{
std::cout<<"Sleeping.....\n";
sleep(1);
}
return 0;
}
Compiled this program and generated executable my_prog
my Qprocess looks as shown below
QProcess* process= new Qprocess();
QString command = "my_prog";
process->start(command);
process->waitForStarted();
Based on some event I tried sending SIGINT in following ways
process->kill();
process->close();
process->write("0x03");
process->terminate();
kill(process->pid(), SIGINT);
QString command = kill -9 <PID>;
QByteArray ba = command.toLatin1();
system(ba.data());
Even after trying all these things I am not able to receive the SIGINT in my program.
Please help me in finding the correct way to implement this.
EDIT1: Updated the example program.
I tried to explain the problem and ignored syntax errors in the example.
Sorry for that.
Thanks in advance.
Besides from several syntax errors/typos in your example, which will prevent the code from even compiling, the program which you try to kill has two and a half issues:
The signal handler has the wrong signature, it receives an integer parameter as shown in the manpage. This won't even compile with g++.
In main no event loop or similar is started. Thus when you execute the binary, it registers the signal handler, and exits immediately after that, because signal() is non-blocking.
From the signal() manpage:
Avoid its use: use sigaction(2) instead.
Edit
Point 1 and 2 are obsoleted by EDIT1 of OP, point 3 remains.
As pointed out by Murphy, QProcess captures stdout/stderr and makes it available through a QIODevice interface. If you don't forward the subprocess output to the parent process, you won't see any output.
After forwarding the process channels, you must also send the correct signal if you want your signal handler to be called. The process->kill() sends a SIGKILL not a SIGINT, so your signal handler wouldn't be invoked. Most of your examples for killing the subprocess are sending the wrong signal.
Finally, be sure that your command is actually starting. I had to specify a relative local path ./my_prog in order to have the process start successfully.
Here is some code based on your incomplete example that works for me:
#include <QProcess>
#include <QDebug>
#include <unistd.h>
#include <csignal>
int main(int argc, char *argv[])
{
QProcess *process = new QProcess();
// Start process from local directory
QString command = "./my_prog";
// Forward output of process to parent stdout/stderr
process->setProcessChannelMode(QProcess::ForwardedChannels);
process->start(command);
// Ensure process starts successfully; wait indefinitely
if(process->waitForStarted(-1))
{
qDebug() << "Process started.";
// Wait a little before sending signal
sleep(1);
// Send the correct signal
kill(process->pid(), SIGINT);
} else {
qDebug() << "Failed to start process.";
}
}

save variable argument list for fprintf calls

I am writing a heavy multi threaded [>170 threads] c++11 program. Each thread is logging information into one file used by all threads. For performance reasons I want to create a log thread which is writing the information via fprintf() into the global file. I have no idea how to organize the structure into which the worker threads are writing the information which can be then read by the log thread.
Why do I not call sprintf() in each worker thread and then just provide the output buffer to the log thread? For the formatted output into the log file I am using a locale in the fprintf() functions which is different than in the rest of the thread. Therefore I would have to switch and lock/guard permanently the xprintf() calls in order to differ the locale output.
In the log thread I have one locale setting used for the whole output while the worker threads have their locale version.
Another reason for the log thread is that I have to "group" the output otherwise the information from each worker thread would not be in a block:
Wrong:
Information A Thread #1
Information A Thread #2
Information B Thread #1
Information B Thread #2
Correct:
Information A Thread #1
Information B Thread #1
Information A Thread #2
Information B Thread #2
In order to achieve this grouping I have to guard the output in each worker thread which is slowing the thread execution time.
How can I save the va_list into a structure that way it can be read by the log thread and passed back to fprintf()?
I don't see how this would be done easily using the legacy C vprintf with va_lists. As you want to pass things around between threads, sooner or later you will need to use the heap in some way.
Below is a solution that uses Boost.Format for the formatting and Boost.Variant for parameter passing. The example is complete and working if you concatenate the following code blocks in order. If you compile with GCC, you need to pass the -pthread linker flag. And of course, you'll also need the two Boost libraries which are header-only, however. Here are the headers we will use.
#include <condition_variable>
#include <iostream>
#include <list>
#include <locale>
#include <mutex>
#include <random>
#include <string>
#include <thread>
#include <utility>
#include <vector>
#include <boost/format.hpp>
#include <boost/variant.hpp>
At first, we need some mechanism to asynchronously execute some tasks, in this case, print our logging messages. Since the concept is general, I use an “abstract” base class Spooler for this. Its code is based on Herb Sutter's talk “Lock-Free Programming (or, Juggling Razor Blades)” on CppCon 2014 (part 1, part 2). I'm not going into detail about this code because it is mostly scaffolding not directly related to your question and I assume you already have this piece of functionality in place. My Spooler uses a std::list protected by a std::mutex as a task queue. It might be worthwhile to consider using a lock-free data structure instead.
class Spooler
{
private:
bool done_ {};
std::list<std::function<void(void)>> queue_ {};
std::mutex mutex_ {};
std::condition_variable condvar_ {};
std::thread worker_ {};
public:
Spooler() : worker_ {[this](){ work(); }}
{
}
~Spooler()
{
auto poison = [this](){ done_ = true; };
this->submit(std::move(poison));
if (this->worker_.joinable())
this->worker_.join();
}
protected:
void
submit(std::function<void(void)> task)
{
// This is basically a push_back but avoids potentially blocking
// calls while in the critical section.
decltype(this->queue_) tmp {std::move(task)};
{
std::unique_lock<std::mutex> lck {this->mutex_};
this->queue_.splice(this->queue_.cend(), tmp);
}
this->condvar_.notify_all();
}
private:
void
work()
{
do
{
std::unique_lock<std::mutex> lck {this->mutex_};
while (this->queue_.empty())
this->condvar_.wait(lck);
const auto task = std::move(this->queue_.front());
this->queue_.pop_front();
lck.unlock();
task();
}
while (!this->done_);
}
};
From the Spooler, we now derive a Logger that (privately) inherits its asynchronous capabilities from the Spooler and adds the logging specific functionality. It has only one function member called log that takes as parameters a format string and zero or more arguments to format into it as a std::vector of boost::variants.
Unfortunately, this limits us to a fixed number of types we can support but that shouldn't be a large problem since the C printf doesn't support arbitrary types either. For the sake of this example, I'm only using int and double but you can extend the list with std::strings, void * pointers or what have you.
The log function constructs a lambda expression that creates a boost::format object, feeds it all the arguments and then writes it to std::log or wherever you want the formatted message to go.
The constructor of boost::format has an overload that accepts the format string and a locale. You might be interested in this one since you have mentioned setting a custom locale in the comments. The usual constructor only takes a single argument, the format string.
Note how all formatting and outputting is done on the spooler's thread.
class Logger : Spooler
{
public:
void
log(const std::string& fmt,
const std::vector<boost::variant<int, double>>& args)
{
auto task = [fmt, args](){
boost::format msg {fmt, std::locale {"C"}}; // your locale here
for (const auto& arg : args)
msg % arg; // feed the next argument
std::clog << msg << std::endl; // print the formatted message
};
this->submit(std::move(task));
}
};
This is all it takes. We can now use the Logger like in this example. It is important that all worker threads are join() ed before the Logger is destructed or it won't process all messages.
int
main()
{
Logger logger {};
std::vector<std::thread> threads {};
std::random_device rnddev {};
for (int i = 0; i < 4; ++i)
{
const auto seed = rnddev();
auto task = [&logger, i, seed](){
std::default_random_engine rndeng {seed};
std::uniform_real_distribution<double> rnddist {0.0, 0.5};
for (double p = 0.0; p < 1.0; p += rnddist(rndeng))
logger.log("thread #%d is %6.2f %% done", {i, 100.0 * p});
logger.log("thread #%d has completed its work", {i});
};
threads.emplace_back(std::move(task));
}
for (auto& thread : threads)
thread.join();
}
Possible output:
thread #1 is 0.00 % done
thread #0 is 0.00 % done
thread #0 is 26.84 % done
thread #0 is 76.15 % done
thread #3 is 0.00 % done
thread #0 has completed its work
thread #3 is 34.70 % done
thread #3 is 78.92 % done
thread #3 is 91.89 % done
thread #3 has completed its work
thread #1 is 26.98 % done
thread #1 is 73.84 % done
thread #1 has completed its work
thread #2 is 0.00 % done
thread #2 is 10.17 % done
thread #2 is 29.85 % done
thread #2 is 79.03 % done
thread #2 has completed its work

Can i read the exit value from the console application?

I want to read the exit value from my console application to exit all the related threads with that application before exit.
This work for me on Windows try it
#include <csignal>
#include <iostream>
#include <ostream>
#include <string>
using namespace std;
namespace
{
volatile sig_atomic_t exit;
void signal_handler(int sig)
{
signal(sig, signal_handler);
exit= 1;
}
}
int main()
{
signal(SIGINT, signal_handler);
signal(SIGTERM, signal_handler);
#ifdef SIGBREAK
signal(SIGBREAK, signal_handler);
#endif
while (!exit)
{
/* do something */
}
// Catch signal here
}
Take a look at https://stackoverflow.com/questions/298498/c-console-breaking. The standard library you need to use is csignal
What you can do is register for signals which force your app to close (SIGTERM) and perform logic there, like exiting your multiple threads. This post suggests that this should work with windows as well.
You could also register a function with atexit which seems to catch normal exit from main() etc, not sure if closing the terminal will count as "normal exit".
Edit: Ok so it seems you want to be notified as soon as the process exits. Sorry, I misread your question due to the term "exit value". Well if you start the process via CreateProcess() API, you should be able to do WaitForSingleObject() on the handle. This function will block until the process exited. So you can place all the code which you want to be executed after the process stopped after this call, and all should be fine.
If you in fact want the exit code of a process (return X in main()):
Programmatically, you can use GetExitCodeProcess() from WinAPI:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms683189(v=vs.85).aspx
In the shell, use the %errorlevel% variable.

Automation implementation using Busy Waiting or Threads in c++

I am trying to automate the handler equipment(a robot picks a chip and put it onto a hardware platform) with the following requirement:
1.There are 6 sites for the handler , once handler puts a device onto that site, handler will return an errorcode:
code1 for ready to test, code2 for error, and if in process no code have returned.
2.There is a master PC that controls the handler operation, and the communication b/w master and site PCs are using Staf
3.I need to use that code to run some tests(which already implemented and working properly).
Handler puts the device in a FIFO order, first site returns code first, and last site returns code last.
4.The Site PC is acting passively, which master PC will determine when to run and how to run the tests. Site PC will only know if handler is ready then execute the tests.
So my question would be: In this case, for the site-PCs(Windows based with perl and .net enabled), is busy waiting method better or is the wait condition mechanism suits better:
For example: the sample code would be:
void runTestonSite()
{
for(;;)
{
if(returnCode == code1)
{
testStart(arg1,arg2,arg3);
}
}
}
or is there any better way to do this kind of task?
#include <boost/thread.hpp>
void getReturnCode() {
// do stuff
}
void RunTestOnSite() {
// do stuff
}
int main (int argc, char ** argv) {
using namespace boost;
thread thread_1 = thread(getReturnCode);
thread thread_2 = thread(RunTestOnSite);
// do other stuff
thread_2.join();
thread_1.join();
return 0;
}
Please advise,
thanks

program get stuck in getenv()

I am overloading "malloc" by pre-loading a library. In this custom "malloc", i am using environment variable to distinguish my program to use my custom "malloc" from the general "malloc".
The problem is that, after several "mallocs" the program gets stuck inside getenv() call. I am not able to figure out why the program is getting stuck inside it.
The code is the following:
void* PerfTrackMallocInterposition::Malloc(size_t size) {
// Malloc with statistics
pthread_mutex_lock(&fgPTMutex);
char *checkCDBEnd=NULL;
static const char* CDBEndEnv = "checkCDBEnd";
checkCDBEnd = getenv(CDBEndEnv); //program gets stuck here
if(checkCDBEnd!=NULL)
{
if(checkCDBEnd[0]=='1')
{
if(size>1024)
{
void *result = Alloc(size); //Call to custom malloc
pthread_mutex_unlock(&fgPTMutex);
return result;
}
}
}
void* result = (*fPMalloc)(size); //call to normal malloc
pthread_mutex_unlock(&fgPTMutex);
return result;
}
I also get a bus error at same position while using this library with vim editor.
Please help me.
Thank You
Are you sure the program gets stuck on the getenv() call? I would be more suspicious of the mutexes: pthread_mutex_lock(&fgPTMutex); will block if another thread holds the mutex

Resources