1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
|
#include <unistd.h>
#include <sys/time.h>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <ostream>
#include <string>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
struct timestat
{
pthread_t pid;
int n;
timeval start, stop;
std::string str;
timestat() : pid(0), n(0) { const timeval c = { 0, 0 }; start = stop = c; }
};
std::ostream& operator<<(std::ostream& os, const timeval &tv)
{
using namespace std;
os << tv.tv_sec << '.' << setw(6) << setfill('0') << tv.tv_usec;
return os;
}
std::ostream& operator<<(std::ostream& os, const timestat &ti)
{
os << ti.pid << ' ' << ti.n << ' ' << ti.start << ' ' << ti.stop;
return os;
}
void* func(void *param)
{
timestat* info = reinterpret_cast<timestat*>(param);
gettimeofday(&info->start, 0);
for (int i = 0; i < info->n; ++i)
{
std::ostringstream os;
os << "hello " << i;
info->str = os.str();
}
gettimeofday(&info->stop, 0);
return param;
}
void* func2(void *param)
{
timestat* info = reinterpret_cast<timestat*>(param);
gettimeofday(&info->start, 0);
for (int i = 0; i < info->n; ++i)
{
char buf[255];
snprintf(buf, sizeof(buf), "hello %d", i);
info->str = buf;
}
gettimeofday(&info->stop, 0);
return param;
}
timeval diff(const timeval &a, const timeval &b)
{
timeval c = { a.tv_sec - b.tv_sec, a.tv_usec - b.tv_usec };
if (c.tv_usec < 0)
{
// carry
--c.tv_sec;
c.tv_usec += 1000000;
}
return c;
}
int main(int argc, char *argv[])
{
int nthreads = atoi(argv[1]);
int niters = atoi(argv[2]);
std::vector<timestat> ti(nthreads);
for (int i = 0; i < nthreads; ++i)
{
ti[i].n = niters;
pthread_create(&ti[i].pid, NULL, (i % 2 ? func2 : func), &ti[i]);
}
for (int i = 0; i < nthreads; ++i)
{
pthread_join(ti[i].pid, NULL);
}
for (int i = 0; i < nthreads; ++i)
{
timeval dt = diff(ti[i].stop, ti[i].start);
std::cout << "thread " << i << ": delay " << dt << std::endl;
}
return 0;
}
| |