BOOST_FIXTURE_TEST_CASE( connection_details_reported_when_connection_is_established, link_layer_only_connect_callback )
{
    respond_to( 37, {
        0xc5, 0x22,                         // header
        0x3c, 0x1c, 0x62, 0x92, 0xf0, 0x48, // InitA: 48:f0:92:62:1c:3c (random)
        0x47, 0x11, 0x08, 0x15, 0x0f, 0xc0, // AdvA:  c0:0f:15:08:11:47 (random)
        0x5a, 0xb3, 0x9a, 0xaf,             // Access Address
        0x08, 0x81, 0xf6,                   // CRC Init
        0x03,                               // transmit window size
        0x0b, 0x00,                         // window offset
        0x18, 0x00,                         // interval (30ms)
        0x02, 0x00,                         // slave latency
        0x48, 0x05,                         // connection timeout
        0xf3, 0x5f, 0x1f, 0x7f, 0x1f,       // used channel map
        0xaa                                // hop increment and sleep clock accuracy (10 and 50ppm)
    } );
    add_connection_event_respond( { 0, 1 } );
    run( 2 );

    const auto reported_details = only_connect_callback.reported_details;

    static const std::uint8_t map_data[] = { 0xf3, 0x5f, 0x1f, 0x7f, 0x1f };
    bluetoe::link_layer::channel_map channels;
    channels.reset( &map_data[ 0 ], 10 );

    BOOST_CHECK( equal( reported_details.channels(), channels ) );
    BOOST_CHECK_EQUAL( reported_details.interval(), 0x18 );
    BOOST_CHECK_EQUAL( reported_details.latency(), 2 );
    BOOST_CHECK_EQUAL( reported_details.timeout(), 0x548 );
    BOOST_CHECK_EQUAL( reported_details.cumulated_sleep_clock_accuracy_ppm(), 50 + 100 );
}
Esempio n. 2
0
void measure_latency(int n, StatVector& stats){
	const int ntrials = NTRIALS;
	assrt(stats.getSize() >= ntrials);
	stats.flush();
	int *npages = (int *)_mm_malloc(1l*4096*n, 4096);
	for(int i=0; i < ntrials; i++){
		double cycles = latency(n, npages);
		stats.insert(cycles);
	}
	_mm_free(npages);
}
Esempio n. 3
0
auto consume(T& buffer, size_t count)
{
	unsigned long sum_id = 0;
	
	auto l = latency([&](){
		while(!buffer.try_consume([&](Event& e) {
			sum_id += e.id;
		}));
	}, count, 99.9);
	
	return std::make_pair(l, sum_id);
}
Esempio n. 4
0
auto produce(T& buffer, size_t count)
{	
	unsigned long i = 0;
	
	auto l = latency([&](){
		while(!buffer.try_push([&](Event& e) {
			e.id = i;
			i++;
		}));
	}, count, 99.9);
	
	return l;
}
ssize_t AudioALSAStreamOut::write(const void *buffer, size_t bytes)
{
    ALOGV("%s(), buffer = %p, bytes = %d", __FUNCTION__, buffer, bytes);

    size_t outputSize = 0;
    if (mSuspendCount > 0 ||
        (mStreamOutType == STREAM_OUT_HDMI_STEREO && mSuspendStreamOutHDMIStereoCount > 0) ||
         (mStreamManager->isModeInPhoneCall() == true && mStreamOutType  != STREAM_OUT_PRIMARY))
    {
        // here to sleep a buffer size latency and return.
        ALOGV("%s(), mStreamOutType = %d, mSuspendCount = %u, mSuspendStreamOutHDMIStereoCount = %d",
              __FUNCTION__, mStreamOutType, mSuspendCount, mSuspendStreamOutHDMIStereoCount);
        usleep(latency() * 1000);
        mPresentedBytes += bytes;
        return bytes;
    }

    AudioAutoTimeoutLock _l(mLock);

    status_t status = NO_ERROR;

    /// check open
    if (mStandby == true)
    {
        status = open();
        mStreamManager->setMasterVolume(mStreamManager->getMasterVolume());
//#ifdef MTK_DYNAMIC_CHANGE_HAL_BUFFER_SIZE
        setLowLatencyMode(mLowLatencyMode);
//#endif
        mPlaybackHandler->setFirstDataWriteFlag(true);
    }
    else
    {
        ASSERT(mPlaybackHandler != NULL);
        mPlaybackHandler->setFirstDataWriteFlag(false);
    }

    WritePcmDumpData(buffer, bytes);

    /// write pcm data
    ASSERT(mPlaybackHandler != NULL);
    outputSize = mPlaybackHandler->write(buffer, bytes);
    mPresentedBytes += outputSize;
    //ALOGD("%s(), outputSize = %d, bytes = %d,mPresentedBytes=%d", __FUNCTION__, outputSize, bytes, mPresentedBytes);
    return outputSize;
}
BOOST_FIXTURE_TEST_CASE( connection_details_reported_when_connection_is_updates, link_layer_only_changed_callback )
{
    respond_to( 37, valid_connection_request_pdu );
    add_connection_update_request( 5, 6, 40, 1, 25, 2 );
    ll_empty_pdus( 120 );
    run( 3u );

    static const std::uint8_t map_data[] = { 0xff, 0xff, 0xff, 0xff, 0x1f };
    bluetoe::link_layer::channel_map channels;
    channels.reset( &map_data[ 0 ], 10 );

    const auto reported_details = only_changed_callback.reported_details;
    BOOST_CHECK( equal( reported_details.channels(), channels ) );
    BOOST_CHECK_EQUAL( reported_details.interval(), 40 );
    BOOST_CHECK_EQUAL( reported_details.latency(), 1 );
    BOOST_CHECK_EQUAL( reported_details.timeout(), 25 );
    BOOST_CHECK_EQUAL( reported_details.cumulated_sleep_clock_accuracy_ppm(), 50 + 100 );
}
Esempio n. 7
0
void Output::status()
{
    qint64 ct = total_written_ / bytes_per_millisecond_ - latency();
    if (ct < 0)
    {
        ct = 0;
    }

    if (ct > current_milliseconds_)
    {
        current_milliseconds_ = ct;
        dispatch(current_milliseconds_,
                 total_written_,
                 kbps_,
                 frequency_,
                 precision_,
                 channels_);
    }
}
Esempio n. 8
0
void AbstractImageGrabber::grab()
{
    QImage frame;//this stores grabbed image
    QEventLoop latencyLoop;
    QElapsedTimer timer;

    if (!m_timer) {
        timer.start();
    }

    m_prevPts = -1;
    int pts = -1;

    Q_FOREVER {
        frame = captureFrame();
        
        setGrabbedFrameCount(grabbedFrameCount() + 1);
        
        pts = m_timer ? m_timer->elapsed() : timer.elapsed();
        if (m_prevPts != pts) {
            m_prevPts = pts;
            Q_EMIT frameAvailable(frame, pts);
        }

        //check if we must finish grabbing
        if (isStopRequest() || isPauseRequest())
            break;

        //wait for set by user milliseconds
        QTimer::singleShot(latency(), &latencyLoop, SLOT(quit()));
        latencyLoop.exec();
    }

    setState(isStopRequest() ? AbstractGrabber::StoppedState : AbstractGrabber::SuspendedState);

    if (isStopRequest())
        m_prevPts = -1;

    //reset stop and pause flags
    setStopRequest(false);
    setPauseRequest(false);
}
net_result LinuxNetworkInterface::nrecv
( LinkLayerAddress *addr, uint8_t *payload, size_t &length ) {
	fd_set readfds;
	int err;
	struct msghdr msg;
	struct cmsghdr *cmsg;
	struct {
		struct cmsghdr cm;
		char control[256];
	} control;
	struct sockaddr_ll remote;        
	struct iovec sgentry;
	net_result ret = net_succeed;
	bool got_net_lock;

	LinuxTimestamperGeneric *gtimestamper;
  
	struct timeval timeout = { 0, 16000 }; // 16 ms

	if( !net_lock.lock( &got_net_lock )) {
		fprintf( stderr, "A Failed to lock mutex\n" );
		return net_fatal;
	}
	if( !got_net_lock ) {
		return net_trfail;
	}

	FD_ZERO( &readfds );
	FD_SET( sd_event, &readfds );
  
	err = select( sd_event+1, &readfds, NULL, NULL, &timeout );		
	if( err == 0 ) {
		ret = net_trfail;
		goto done;
	} else if( err == -1 ) {
		if( err == EINTR ) {
			// Caught signal
			XPTPD_ERROR( "select() recv signal" );
			ret = net_trfail;
			goto done;
		} else {
			XPTPD_ERROR( "select() failed" );
			ret = net_fatal;
			goto done;
    }
	} else if( !FD_ISSET( sd_event, &readfds )) {
		ret = net_trfail;
		goto done;
	}
  
	memset( &msg, 0, sizeof( msg ));
  
	msg.msg_iov = &sgentry;
	msg.msg_iovlen = 1;
  
	sgentry.iov_base = payload;
	sgentry.iov_len = length;
  
	memset( &remote, 0, sizeof(remote));
	msg.msg_name = (caddr_t) &remote;
	msg.msg_namelen = sizeof( remote );
	msg.msg_control = &control;
	msg.msg_controllen = sizeof(control);
  
	err = recvmsg( sd_event, &msg, 0 );
	if( err < 0 ) {
		if( errno == ENOMSG ) {
			fprintf( stderr, "Got ENOMSG: %s:%d\n", __FILE__, __LINE__ );
			ret = net_trfail;
			goto done;
		}
		XPTPD_ERROR( "recvmsg() failed: %s", strerror(errno) );
		ret = net_fatal;
		goto done;
	}
	*addr = LinkLayerAddress( remote.sll_addr );
  
	gtimestamper = dynamic_cast<LinuxTimestamperGeneric *>(timestamper);
	if( err > 0 && !(payload[0] & 0x8) && gtimestamper != NULL ) {
		/* Retrieve the timestamp */
		cmsg = CMSG_FIRSTHDR(&msg);
		while( cmsg != NULL ) {
			if
				( cmsg->cmsg_level == SOL_SOCKET &&
				  cmsg->cmsg_type == SO_TIMESTAMPING ) {
				Timestamp latency( RX_PHY_TIME, 0, 0 );
				struct timespec *ts_device, *ts_system;
				Timestamp device, system; 
				ts_system = ((struct timespec *) CMSG_DATA(cmsg)) + 1;
				system = tsToTimestamp( ts_system );
				ts_device = ts_system + 1; device = tsToTimestamp( ts_device );
				device = device - latency;
				gtimestamper->pushRXTimestamp( &device );
				break;    
			}
			cmsg = CMSG_NXTHDR(&msg,cmsg);
		}
	}
  
	length = err;

 done:
	if( !net_lock.unlock()) {
		fprintf( stderr, "A Failed to unlock, %d\n", err );
		return net_fatal;
	}

	return ret;		
}
int LinuxTimestamperGeneric::HWTimestamper_txtimestamp
( PortIdentity *identity, uint16_t sequenceId, Timestamp &timestamp,
  unsigned &clock_value, bool last ) {
	int err;
	int ret = -72;
	struct msghdr msg;
	struct cmsghdr *cmsg;
	struct sockaddr_ll remote;        
	struct iovec sgentry;
	struct {
		struct cmsghdr cm;
		char control[256];
	} control;
	Timestamp latency( TX_PHY_TIME, 0, 0 );
     
	if( sd == -1 ) return -1;
	memset( &msg, 0, sizeof( msg ));
    
	msg.msg_iov = &sgentry;
	msg.msg_iovlen = 1;
		
	sgentry.iov_base = NULL;
	sgentry.iov_len = 0;
		
	memset( &remote, 0, sizeof(remote));
	msg.msg_name = (caddr_t) &remote;
	msg.msg_namelen = sizeof( remote );
	msg.msg_control = &control;
	msg.msg_controllen = sizeof(control);

	err = recvmsg( sd, &msg, MSG_ERRQUEUE );
	if( err == -1 ) {
		if( errno == EAGAIN ) {
			ret = -72;
			goto done;
		}
		else {
			ret = -1;
			goto done;
		}
	}
    
	// Retrieve the timestamp
	cmsg = CMSG_FIRSTHDR(&msg);
	while( cmsg != NULL ) {
		if( cmsg->cmsg_level == SOL_SOCKET &&
			cmsg->cmsg_type == SO_TIMESTAMPING ) {
			struct timespec *ts_device, *ts_system;
			Timestamp device, system; 
			ts_system = ((struct timespec *) CMSG_DATA(cmsg)) + 1;
			system = tsToTimestamp( ts_system );
			ts_device = ts_system + 1; device = tsToTimestamp( ts_device );
			system._version = version;
			device = device + latency;
			device._version = version;
			timestamp = device;
			ret = 0;
			break;    
		}
		cmsg = CMSG_NXTHDR(&msg,cmsg);
	}

	if( ret != 0 ) {
		fprintf( stderr, "Received a error message, but didn't find a valid timestamp\n" );
	}
		
 done:
	if( ret == 0 || last ) {
		net_lock->unlock();
	}
		
	return ret;
}
Esempio n. 11
0
int main( int argc, char **argv )
{
    TEST(( PACKETSIZE % 8 ) == 0 );
    co::init( argc, argv );

    for( size_t i = 0; types[i] != co::CONNECTIONTYPE_NONE; ++i )
    {
        co::ConnectionDescriptionPtr desc = new co::ConnectionDescription;
        desc->type = types[i];

        co::ConnectionPtr writer;
        co::ConnectionPtr listener;

        if( !_initialize( desc, listener, writer ))
            continue;

        Reader readThread( listener );
        if( desc->type != co::CONNECTIONTYPE_RSP )
            TEST( writer->connect( ));

        uint64_t out[ PACKETSIZE / 8 ];

        lunchbox::Clock clock;
        uint64_t sequence = 0;

        while( clock.getTime64() < RUNTIME )
        {
            out[0] = ++sequence;
            TEST( writer->send( out, PACKETSIZE ));
        }

        out[0] = 0xdeadbeef;
        TEST( writer->send( out, PACKETSIZE ));

        s_done.waitEQ( true );
        writer->close();
        readThread.join();
        listener->close();
        const float bwTime = clock.getTimef();
        const uint64_t numBW = sequence;

        TEST( _initialize( desc, listener, writer ));
        Latency latency( listener );
        if( desc->type != co::CONNECTIONTYPE_RSP )
            TEST( writer->connect( ));
        sequence = 0;
        clock.reset();

        while( clock.getTime64() < RUNTIME )
        {
            ++sequence;
            TEST( writer->send( &sequence, sizeof( uint64_t )));
        }

        sequence = 0xC0FFEE;
        TEST( writer->send( &sequence, sizeof( uint64_t )));

        s_done.waitEQ( true );
        writer->close();
        latency.join();
        listener->close();

        const float latencyTime = clock.getTimef();
        const float mFactor = 1024.f / 1024.f * 1000.f;

        std::cout << desc->type << ": "
                  << (numBW+1) * PACKETSIZE / mFactor / bwTime
                  << " MBps, " << (sequence+1) / mFactor / latencyTime
                  << " Mpps" << std::endl;

        if( listener == writer )
            listener = 0;

        TESTINFO( !listener || listener->getRefCount() == 1,
                  listener->getRefCount());
        TEST( writer->getRefCount() == 1 );
    }

    co::exit();
    return EXIT_SUCCESS;
}
Esempio n. 12
0
int
main(int ac, char **av)
{
	char	*server;
	int     i, prog;
	int	c;
	int	shutdown = 0;
	uint64	total = 0;
	uint64	usecs = 0;
	double	avg;
	char	*name = av[0];
	char	file[1024];
	char	*usage = "[-d] [-e] [-S] serverhost [port] < list\n";

	while (( c = getopt(ac, av, "deS")) != EOF) {
		switch(c) {
		case 'd':
			debug++;
			break;
		case 'e':
			echo++;
			break;
		case 'S': /* shutdown serverhost */
			shutdown = 1;
			break;
		default:
			lmbench_usage(ac, av, usage);
			break;
		}
	}
	
	if (optind >= ac || optind < ac - 2) {
		lmbench_usage(ac, av, usage);
		exit(0);
	}
	server = av[optind++];

	if (optind < ac && atoi(av[optind]) != 0) {
		prog = -atoi(av[optind]);
	} else {
		prog = -80;
	}

	if (shutdown) {
		killhttp(server, prog);
		exit(0);
	}

	i = 0;
	buf = valloc(XFERSIZE);
	bzero(buf, XFERSIZE);
	while (fgets(file, sizeof(file), stdin)) {
		chop(file);
		start(0);
		total += http(server, file, prog);
		usecs += stop(0,0);
		i++;
	}
	avg = total;
	avg /= (i - 1);
	if (avg > 1000) {
		avg /= 1000;
		fprintf(stderr, "Avg xfer: %.1fKB, ", avg);
	} else {
		fprintf(stderr, "Avg xfer %d, ", (int)avg);
	}
	settime(usecs);
	latency((uint64)1, total);
	exit(0);
}
Esempio n. 13
0
void MainWindow::setupCustomPlot(QCustomPlot *customPlot)
{
/*
    int count = simulation->getGlobalRepository()->getRepositoryList().count();
    QVector<double> discovery(count), latency(count);

    int i = 0;

    Particle * particle;
    //for (int z=simulation->getExternalFile()->getExternalFileList().count()-1; z>=0; z-- )
    for (int z=simulation->getGlobalRepository()->getRepositoryList().count()-1; z>=0; z-- )
    {
        particle = simulation->getGlobalRepository()->getRepositoryList().at(z);
        discovery[i] = particle->getPerformanceDiscovery();
        latency[i] = particle->getPerformanceLatency();
        i++;
    }
*/

    //customPlot->setLocale(QLocale(QLocale::English, QLocale::UnitedKingdom)); // period as decimal separator and comma as thousand separator
    customPlot->legend->setVisible(true);
    QFont legendFont = font();  // start out with MainWindow's font..
    legendFont.setPointSize(9); // and make a bit smaller for legend
    customPlot->legend->setFont(legendFont);
    customPlot->legend->setBrush(QBrush(QColor(255,255,255,230)));
    // by default, the legend is in the inset layout of the main axis rect. So this is how we access it to change legend placement:
    customPlot->axisRect()->insetLayout()->setInsetAlignment(0, Qt::AlignBottom|Qt::AlignRight);


    customPlot->clearGraphs();

    Particle * particle;
    int count = genericAlgorithmSolutions.count();
    QVector<double> discovery(count), latency(count);
    for (int i = 0; i < count; i++)
    {
        particle = genericAlgorithmSolutions.at(i);
        discovery[i] = particle->getPerformanceDiscovery();
        latency[i] = particle->getPerformanceLatency();
    }


    int countModified = modificatedAlgorithmSolutions.count();
    QVector<double> discoveryModified(countModified), latencyModified(countModified);
    if (ui->checkBoxGrid->isChecked())
    {
        for (int i = 0; i < countModified; i++)
        {
            particle = modificatedAlgorithmSolutions.at(i);
            discoveryModified[i] = particle->getPerformanceDiscovery();
            latencyModified[i] = particle->getPerformanceLatency();
        }
    }

    // create graph and assign data to it:
    customPlot->addGraph();



    if (ui->checkBoxGrid->isChecked())
    {
        customPlot->graph(0)->setName("PSO modificado");
        customPlot->graph(0)->setData(discoveryModified, latencyModified);
        customPlot->graph(0)->setPen(QPen(Qt::green)); // line color blue for first graph
        customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCross, Qt::black, 4));
    }
    else
    {
        customPlot->graph(0)->setName("PSO generico");
        customPlot->graph(0)->setData(discovery, latency);
        customPlot->graph(0)->setPen(QPen(Qt::blue)); // line color blue for first graph
        customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCross, Qt::red, 4));
    }

    customPlot->graph(0)->setLineStyle(QCPGraph::lsLine);



    if (ui->checkBoxComparation->isChecked())
    //if (modified)
    {
        customPlot->addGraph();
        customPlot->graph(1)->setPen(QPen(Qt::green)); // line color green for second graph
        customPlot->graph(1)->setData(discoveryModified, latencyModified);
        customPlot->graph(1)->setLineStyle(QCPGraph::lsLine);
        customPlot->graph(1)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCross, Qt::yellow, 4));
    }

    // give the axes some labels:
    customPlot->xAxis->setLabel("Descubierta");
    customPlot->yAxis->setLabel("Latencia");
    // set axes ranges, so we see all data:
    customPlot->xAxis->setRange(0, 75);
    customPlot->yAxis->setRange(0, 300);

    customPlot->yAxis->grid()->setSubGridVisible(true);

    ui->customPlot->replot();



    // show legend:
    //customPlot->legend->setVisible(true);

/*
    // add two new graphs and set their look:
    customPlot->addGraph();
    customPlot->graph(0)->setPen(QPen(Qt::blue)); // line color blue for first graph
    customPlot->graph(0)->setBrush(QBrush(QColor(0, 0, 255, 20))); // first graph will be filled with translucent blue
    customPlot->addGraph();
    customPlot->graph(1)->setPen(QPen(Qt::red)); // line color red for second graph
    // generate some points of data (y0 for first, y1 for second graph):
    QVector<double> x(250), y0(250), y1(250);
    for (int i=0; i<250; ++i)
    {
      x[i] = i;
      y0[i] = exp(-i/150.0)*cos(i/10.0); // exponentially decaying cosine
      y1[i] = exp(-i/150.0);             // exponential envelope
    }
    // configure right and top axis to show ticks but no labels:
    // (see QCPAxisRect::setupFullAxesBox for a quicker method to do this)
    customPlot->xAxis2->setVisible(true);
    customPlot->xAxis2->setTickLabels(false);
    customPlot->yAxis2->setVisible(true);
    customPlot->yAxis2->setTickLabels(false);
    // make left and bottom axes always transfer their ranges to right and top axes:
    connect(customPlot->xAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->xAxis2, SLOT(setRange(QCPRange)));
    connect(customPlot->yAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->yAxis2, SLOT(setRange(QCPRange)));
    // pass data points to graphs:
    customPlot->graph(0)->setData(x, y0);
    customPlot->graph(1)->setData(x, y1);
    // let the ranges scale themselves so graph 0 fits perfectly in the visible area:
    customPlot->graph(0)->rescaleAxes();
    // same thing for graph 1, but only enlarge ranges (in case graph 1 is smaller than graph 0):
    customPlot->graph(1)->rescaleAxes(true);
    // Note: we could have also just called customPlot->rescaleAxes(); instead
    // Allow user to drag axis ranges with mouse, zoom with mouse wheel and select graphs by clicking:
    customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);

*/

}
Esempio n. 14
0
int
main(int ac, char **av)
{
	char	*name = av[0], *server, *prog;
	int     i, j;
	uint64	total = 0;
	uint64	usecs = 0;
	char	*args[1024];

	if (ac < 5) {
usage:		fprintf(stderr,
		    "Usage: %s hostname [port] remote-clients -p file ...\n",
		    name);
		exit(1);
	}
	server = av[1];
	av++, ac--;	/* eat server */
	if (atoi(av[1]) != 0) {
		prog = av[1];
		av++, ac--;	/* eat port */
	} else {
		prog = "80";	/* http */
	}
	for (i = 1; i < ac; ++i) {
		if (!strcmp("-p", av[i])) {
			i++;
			break;
		}
	}
	args[0] = "rsh";
	args[2] = "http";
	args[3] = server;
	j = 4;
	while (i < ac) {
		args[j++] = av[i++];
	}
	args[j++] = prog;
	args[j] = 0;
	for (i = 1; i < ac; ++i) {
		if (!strcmp("-p", av[i])) {
			break;
		}
		args[1] = av[i];
		for (j = 0; args[j]; j++) {
			printf("%s ", args[j]);
		}
		printf("\n");
		if (fork() == 0) {
			char	name[30];

			sprintf(name, "/tmp/rhttp%d", i);
			creat(name, 0666);
			close(2);
			dup(1);
			execvp(args[0], args);
			perror(args[0]);
			exit(1);
		}
	}
	for (i = 1; i < ac; ++i) {
		if (!strcmp("-p", av[i])) {
			break;
		}
		wait(0);
	}
	system("cat /tmp/rhttp*; rm /tmp/rhttp*"); 
	exit(1);
	for (i = 1; i < ac; ++i) {
		int	fd, n, m = 0;
		float	f1 = 0, f2 = 0;
		char	buf[30];

		if (!strcmp("-p", av[i])) {
			break;
		}
		sprintf(buf, "/tmp/http%d", i);
		fd = open(buf, 0);
		unlink(buf);
		/* 
		 * Avg xfer: 3.9KB, 235.0KB in 2038 millisecs, 115.31 KB/sec
		 */
		n = read(fd, buf, XFERSIZE);
		buf[n] = 0;
		sscanf(buf, "Avg xfer: %fKB, %fKB in %d millisecs,", 
		    &f1, &f2, &m);
		if (m > usecs) {
			usecs = m;
		}
		total += f2;
	}
	total <<= 10;
	usecs *= 1000;
	settime(usecs);
	latency((uint64)1, total);
}
HRESULT CWASAPIRenderFilter::InitAudioClient()
{
  Log("WASAPIRenderFilter::InitAudioClient");
  HRESULT hr = S_OK;
  
  if (m_pSettings->m_hnsPeriod == 0 || m_pSettings->m_hnsPeriod == 1)
  {
    REFERENCE_TIME defaultPeriod(0);
    REFERENCE_TIME minimumPeriod(0);

    hr = m_pAudioClient->GetDevicePeriod(&defaultPeriod, &minimumPeriod);
    if (SUCCEEDED(hr))
    {
      if (m_pSettings->m_hnsPeriod == 0)
        m_pSettings->m_hnsPeriod = defaultPeriod;
      else
        m_pSettings->m_hnsPeriod = minimumPeriod;
      Log("WASAPIRenderFilter::InitAudioClient using device period from driver %I64u ms", m_pSettings->m_hnsPeriod / 10000);
    }
    else
    {
      Log("WASAPIRenderFilter::InitAudioClient failed to get device period from driver (0x%08x) - using 50 ms", hr); 
      m_pSettings->m_hnsPeriod = 500000; //50 ms is the best according to James @Slysoft
    }
  }

  WAVEFORMATEXTENSIBLE* pwfxAccepted = NULL;
  hr = IsFormatSupported(m_pInputFormat, &pwfxAccepted);
  if (FAILED(hr))
  {
    SAFE_DELETE_WAVEFORMATEX(pwfxAccepted);
    return hr;
  }

  GetBufferSize((WAVEFORMATEX*)pwfxAccepted, &m_pSettings->m_hnsPeriod);

  if (SUCCEEDED(hr))
    hr = m_pAudioClient->Initialize(m_pSettings->m_WASAPIShareMode, m_dwStreamFlags,
	                                m_pSettings->m_hnsPeriod, m_pSettings->m_hnsPeriod, (WAVEFORMATEX*)pwfxAccepted, NULL);

  if (FAILED(hr) && hr != AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED)
  {
    Log("WASAPIRenderFilter::InitAudioClient Initialize failed (0x%08x)", hr);
    SAFE_DELETE_WAVEFORMATEX(pwfxAccepted);
    return hr;
  }

  if (hr == S_OK)
  {
    SAFE_RELEASE(m_pAudioClock);
    hr = m_pAudioClient->GetService(__uuidof(IAudioClock), (void**)&m_pAudioClock);
    if (SUCCEEDED(hr))
      m_pAudioClock->GetFrequency(&m_nHWfreq);
    else
      Log("WASAPIRenderFilter::IAudioClock not found!");
  }

  if (hr == AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED) 
  {
    // if the buffer size was not aligned, need to do the alignment dance
    Log("WASAPIRenderFilter::InitAudioClient Buffer size not aligned. Realigning");

    // get the buffer size, which will be aligned
    hr = m_pAudioClient->GetBufferSize(&m_nFramesInBuffer);

    // throw away this IAudioClient
    SAFE_RELEASE(m_pAudioClient);

    // calculate the new aligned periodicity
    m_pSettings->m_hnsPeriod = // hns =
                  (REFERENCE_TIME)(
                  10000.0 * // (hns / ms) *
                  1000 * // (ms / s) *
                  m_nFramesInBuffer / // frames /
                  m_pInputFormat->Format.nSamplesPerSec  // (frames / s)
                  + 0.5 // rounding
    );

    if (SUCCEEDED(hr)) 
      hr = CreateAudioClient();
      
    Log("WASAPIRenderFilter::InitAudioClient Trying again with periodicity of %I64u hundred-nanoseconds, or %u frames", m_pSettings->m_hnsPeriod, m_nFramesInBuffer);

    if (SUCCEEDED (hr)) 
      hr = m_pAudioClient->Initialize(m_pSettings->m_WASAPIShareMode, m_dwStreamFlags, 
	                                    m_pSettings->m_hnsPeriod, m_pSettings->m_hnsPeriod, (WAVEFORMATEX*)pwfxAccepted, NULL);
 
    if (FAILED(hr))
    {
      Log("WASAPIRenderFilter::InitAudioClient Failed to reinitialize the audio client");
      SAFE_DELETE_WAVEFORMATEX(pwfxAccepted);
      return hr;
    }
    else
    {
      SAFE_RELEASE(m_pAudioClock);
      hr = m_pAudioClient->GetService(__uuidof(IAudioClock), (void**)&m_pAudioClock);
      if (FAILED(hr))
        Log("WASAPIRenderFilter::IAudioClock not found!");
      else
        m_pAudioClock->GetFrequency(&m_nHWfreq);
    }
  } // if (AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED == hr) 

  // get the buffer size, which is aligned
  if (SUCCEEDED(hr)) 
    hr = m_pAudioClient->GetBufferSize(&m_nFramesInBuffer);

  // calculate the new period
  if (SUCCEEDED (hr)) 
    hr = m_pAudioClient->GetService(__uuidof(IAudioRenderClient), (void**)(&m_pRenderClient));

  if (FAILED(hr))
    Log("WASAPIRenderFilter::InitAudioClient service initialization failed (0x%08x)", hr);
  else
    Log("WASAPIRenderer::InitAudioClient service initialization success");

  if (m_pSettings->m_bWASAPIUseEventMode)
  {
    hr = m_pAudioClient->SetEventHandle(m_hDataEvent);
    if (FAILED(hr))
    {
      Log("WASAPIRenderFilter::InitAudioClient SetEventHandle failed (0x%08x)", hr);
      SAFE_DELETE_WAVEFORMATEX(pwfxAccepted);
      return hr;
    }
  }

  REFERENCE_TIME latency(0);
  m_pAudioClient->GetStreamLatency(&latency);
  
  Log("WASAPIRenderFilter::InitAudioClient device reported latency %I64u ms - buffer based latency %I64u ms", 
    latency / 10000, Latency() / 10000);

  // Dynamic format change requires restart for the audio client
  if (m_state != StateStopped)
    StartAudioClient();

  m_bDeviceInitialized = true;

  SAFE_DELETE_WAVEFORMATEX(pwfxAccepted);
  return hr;
}
Esempio n. 16
0
void calc_depth(inst_t *inst_list, int min_index, int max_index) {

    int MAX_REGS;
    int *latest_use_time, *completion_time;
    int t, j;
    int i;
    int max_depth = 0;

    MAX_REGS = number_of_registers();

    latest_use_time = (int *) malloc(MAX_REGS * sizeof (int));
    completion_time = (int *) malloc(MAX_REGS * sizeof (int));

    for (i = 0; i < MAX_REGS; i++) {
        latest_use_time[i] = 0;
        completion_time[i] = 0;
    }

    while (min_index <= max_index) {
        if (inst_list[min_index]->ops[0].t == op_reg && inst_list[min_index]->op != OP_STR && inst_list[min_index]->op != OP_BR) {
            t = max(1, latest_use_time[inst_list[min_index]->ops[0].reg] - latency(inst_list[min_index]) + 1);
        }
        if (inst_list[min_index]->op == OP_IN) { // IN writes to R0
            t = max(1, latest_use_time[0] - latency(inst_list[min_index]) + 1);
        }
        for (j = 1; j <= 2; j++) {
            if (inst_list[min_index]->ops[j].t == op_reg) {
                t = max(t, completion_time[inst_list[min_index]->ops[j].reg]);
            }
        }
        if (inst_list[min_index]->op == OP_STR || inst_list[min_index]->op == OP_BR) { // STR reads from first register
            t = max(t, completion_time[inst_list[min_index]->ops[0].reg]);
        }
        if (inst_list[min_index]->op == OP_OUT) { // OUT reads from R0
            t = max(t, completion_time[0]);
        }
        if (inst_list[min_index]->ops[0].t == op_reg && inst_list[min_index]->op != OP_STR && inst_list[min_index]->op != OP_BR) {
            t = max(t, completion_time[inst_list[min_index]->ops[0].reg] - latency(inst_list[min_index]));
        }
        if (inst_list[min_index]->op == OP_IN) { // IN writes to R0
            t = max(t, completion_time[0] - latency(inst_list[min_index]));
        }
        if (inst_list[min_index]->ops[0].t == op_reg && inst_list[min_index]->op != OP_STR && inst_list[min_index]->op != OP_BR) {
            completion_time[inst_list[min_index]->ops[0].reg] = t + latency(inst_list[min_index]);
        }
        if (inst_list[min_index]->op == OP_IN) { // IN writes to R0
            completion_time[0] = t + latency(inst_list[min_index]);
        }
        for (j = 1; j <= 2; j++) {
            if (inst_list[min_index]->ops[j].t == op_reg) {
                latest_use_time[inst_list[min_index]->ops[j].reg] = max(latest_use_time[inst_list[min_index]->ops[j].reg], t);
            }
        }
        if (inst_list[min_index]->op == OP_STR || inst_list[min_index]->op == OP_BR) { // STR reads from first register
            latest_use_time[inst_list[min_index]->ops[0].reg] = max(latest_use_time[inst_list[min_index]->ops[0].reg], t);
        }
        if (inst_list[min_index]->op == OP_OUT) { // OUT reads from R0
            latest_use_time[0] = max(latest_use_time[0], t);
        }
        inst_list[min_index]->depth = t;
        max_depth = max(max_depth, t);

        min_index++;
    }

    if (inst_list[max_index]->op == OP_BRA) {
        inst_list[max_index]->depth = max_depth;
    }
    
    free(latest_use_time);
    free(completion_time);

    return;
}
void hello(void *args){
  int i;

  for ( i=0; i<10000; ++i)
  latency();
}
Esempio n. 18
0
void MainWindow::setupCustomPlot2(QCustomPlot *customPlot)
{
/*
    int count = simulation->getGlobalRepository()->getRepositoryList().count();
    QVector<double> discovery(count), latency(count);

    int i = 0;

    Particle * particle;
    //for (int z=simulation->getExternalFile()->getExternalFileList().count()-1; z>=0; z-- )
    for (int z=simulation->getGlobalRepository()->getRepositoryList().count()-1; z>=0; z-- )
    {
        particle = simulation->getGlobalRepository()->getRepositoryList().at(z);
        discovery[i] = particle->getPerformanceDiscovery();
        latency[i] = particle->getPerformanceLatency();
        i++;
    }
*/

    customPlot->legend->setVisible(true);
    QFont legendFont = font();  // start out with MainWindow's font..
    legendFont.setPointSize(9); // and make a bit smaller for legend
    customPlot->legend->setFont(legendFont);
    customPlot->legend->setBrush(QBrush(QColor(255,255,255,230)));
    // by default, the legend is in the inset layout of the main axis rect. So this is how we access it to change legend placement:
    customPlot->axisRect()->insetLayout()->setInsetAlignment(0, Qt::AlignBottom|Qt::AlignRight);

    customPlot->clearGraphs();


    Particle * particle;
    int count = genericAlgorithmSolutions.count();
    QVector<double> discovery(count), latency(count);
    for (int i = 0; i < count; i++)
    {
        particle = genericAlgorithmSolutions.at(i);
        discovery[i] = particle->getPerformanceDiscovery();
        latency[i] = particle->getPerformanceLatency();
    }


    int countModified = modificatedAlgorithmSolutions.count();
    QVector<double> discoveryModified(countModified), latencyModified(countModified);
    //if (ui->checkBoxComparation->isChecked())
    //if (comparation)
    //{
        for (int i = 0; i < countModified; i++)
        {
            particle = modificatedAlgorithmSolutions.at(i);
            discoveryModified[i] = particle->getPerformanceDiscovery();
            latencyModified[i] = particle->getPerformanceLatency();
        }
    //}

    // create graph and assign data to it:
    customPlot->addGraph();
    customPlot->graph(0)->setPen(QPen(Qt::blue)); // line color blue for first graph
    customPlot->graph(0)->setData(discovery, latency);
    customPlot->graph(0)->setLineStyle(QCPGraph::lsLine);
    customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCross, Qt::red, 4));
    customPlot->graph(0)->setName("PSO generico");

    customPlot->addGraph();
    customPlot->graph(1)->setPen(QPen(Qt::green)); // line color green for second graph
    customPlot->graph(1)->setData(discoveryModified, latencyModified);
    customPlot->graph(1)->setLineStyle(QCPGraph::lsLine);
    customPlot->graph(1)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCross, Qt::black, 4));
    customPlot->graph(1)->setName("PSO modificado");

    // give the axes some labels:
    customPlot->xAxis->setLabel("Descubierta");
    customPlot->yAxis->setLabel("Latencia");
    // set axes ranges, so we see all data:
    customPlot->xAxis->setRange(0, 75);
    customPlot->yAxis->setRange(0, 300);

    customPlot->yAxis->grid()->setSubGridVisible(true);



    ui->customPlot->replot();

    // show legend:
    //customPlot->legend->setVisible(true);
}