Exemplo n.º 1
0
void ShmSystemV::Close()
{
    ProfilerStart("close");
    int result = shmdt(m_Buffer);
    ProfilerStop("close");
    if (result < 1)
    {
        throw std::ios_base::failure(
            "ERROR: failed to detach shared memory segment of size " +
            std::to_string(m_Size) + " and name " + m_Name +
            ", in call to SystemV shmdt Close\n");
    }

    if (m_RemoveAtClose)
    {
        ProfilerStart("close");
        int remove = shmctl(m_ShmID, IPC_RMID, NULL);
        ProfilerStop("close");
        if (result < 1)
        {
            throw std::ios_base::failure(
                "ERROR: failed to remove shared memory segment of size " +
                std::to_string(m_Size) + " and name " + m_Name +
                ", in call to SystemV shmctl Close\n");
        }
    }

    m_IsOpen = false;
}
Exemplo n.º 2
0
static void
rspamd_worker_term_handler (struct rspamd_worker_signal_handler *sigh, void *arg)
{
	struct timeval tv;

	if (!sigh->worker->wanna_die) {
		rspamd_default_log_function (G_LOG_LEVEL_INFO,
				sigh->worker->srv->server_pool->tag.tagname,
				sigh->worker->srv->server_pool->tag.uid,
				G_STRFUNC,
				"terminating after receiving signal %s",
				g_strsignal (sigh->signo));

		tv.tv_usec = 0;
		if (rspamd_worker_terminate_handlers (sigh->worker)) {
			tv.tv_sec =  SOFT_SHUTDOWN_TIME;
		}
		else {
			tv.tv_sec = 0;
		}

		sigh->worker->wanna_die = 1;
		event_base_loopexit (sigh->base, &tv);
#ifdef WITH_GPERF_TOOLS
		ProfilerStop ();
#endif
		rspamd_worker_stop_accept (sigh->worker);
	}
}
Exemplo n.º 3
0
void int_handler(int sig_num)
{
#ifdef PROFILER
	ProfilerStop();
#endif
	exit(0);
}
Exemplo n.º 4
0
void ShmSystemV::Read(char *buffer, size_t size, size_t start)
{
    CheckSizes(size, start, "in call to Read");
    ProfilerStart("read");
    std::memcpy(buffer, &m_Buffer[start], size);
    ProfilerStop("read");
}
Exemplo n.º 5
0
void ShmSystemV::Write(const char *buffer, size_t size, size_t start)
{
    CheckSizes(size, start, "in call to Write");
    ProfilerStart("write");
    std::memcpy(&m_Buffer[start], buffer, size);
    ProfilerStop("write");
}
Exemplo n.º 6
0
int main(int argc, const char* argv[]) {
    char* alphabet;

    bool verbose = false;
    if (argc == 2 && strcmp(argv[1], "-v") != 0) {
        alphabet = (char*) argv[1];
    } else if (argc == 3) {
        alphabet = (char*) argv[2];
        verbose = true;
    } else {
        alphabet = (char*) "abcdefghijklmnopqrstuvwxyz";
    }

//    char* alphabet = "abcdefghijklmnopqrstuvwxyz@";
//    bool verbose = false;


    latin_square* my_square = malloc(sizeof(latin_square));
    init_latin_square(alphabet, my_square);
    clock_t start = clock();
    #ifdef profile
    ProfilerStart("/tmp/bees.prof");
    #endif
    solve_latin_square(my_square, verbose);
    #ifdef profile
    ProfilerStop();
    #endif
    if (!verbose) print_latin_square(my_square);
    clock_t end = clock();
    return 0;
}
Exemplo n.º 7
0
  // Stops the profiler. There are no request parameters.
  // This returns the profile output, it will also remain present
  // in the working directory.
  Future<http::Response> stop(const http::Request& request)
  {
#ifdef HAS_GPERFTOOLS
    if (!started) {
      return http::BadRequest("Profiler not running.\n");
    }

    LOG(INFO) << "Stopping Profiler";

    ProfilerStop();

    http::OK response;
    response.type = response.PATH;
    response.path = "perftools.out";
    response.headers["Content-Type"] = "application/octet-stream";
    response.headers["Content-Disposition"] =
      strings::format("attachment; filename=%s", PROFILE_FILE).get();

    started = false;
    return response;
#else
    return http::BadRequest(
        "Perftools is disabled. To enable perftools, "
        "configure libprocess with --enable-perftools.\n");
#endif
  }
Exemplo n.º 8
0
int main(int argc, char** argv)
{
    ProfilerStart(argv[0]);
    testing::InitGoogleTest(&argc, argv);
    int n = RUN_ALL_TESTS();
    ProfilerStop();
    return n;
}
Exemplo n.º 9
0
int main(int argc, char **argv)
{
	int ret;
	ProfilerStart("mutool.prof");
	ret = profiled_main(argc, argv);
	ProfilerStop();
	return ret;
}
Exemplo n.º 10
0
 void stop_tracing_here() {
   #ifdef GOOGLE_PROFILER
     ProfilerStop( );
     impl::profile_handler(NULL);
     #ifdef VTRACE_SAMPLED
       VT_USER_END("sampling");
       
       sample();
     #endif
   #endif
 }
Exemplo n.º 11
0
void ShmSystemV::Open(const std::string &name, const Mode openMode)
{
    m_Name = name;
    CheckName();
    m_OpenMode = openMode;

    // not using const
    key_t key = ftok(m_Name.c_str(), static_cast<int>(m_ProjectID));

    switch (m_OpenMode)
    {
    case (Mode::Write):
        ProfilerStart("open");
        m_ShmID = shmget(key, m_Size, IPC_CREAT | 0666);
        ProfilerStop("open");
        break;

    case (Mode::Append):
        ProfilerStart("open");
        m_ShmID = shmget(key, m_Size, 0);
        ProfilerStop("open");
        break;

    case (Mode::Read):
        ProfilerStart("open");
        m_ShmID = shmget(key, m_Size, 0);
        ProfilerStop("open");
        break;

    default:
        throw std::invalid_argument(
            "ERROR: unknown open mode for shared memory segment " + m_Name +
            ", in call to SystemV Open");
    }

    CheckShmID("in call to ShmSystemV shmget at Open");

    m_Buffer = static_cast<char *>(shmat(m_ShmID, nullptr, 0));
    CheckBuffer("in call to SystemV shmat at Open");
    m_IsOpen = false;
}
Exemplo n.º 12
0
int
main (int argc, char *argv[])
{
  gchar *prgdir, *localedir;
  GtkWidget *window, *vbox, *editor; 

  prgdir = am_install_path ();
  if (prgdir)
    {
      localedir = g_build_filename (prgdir, AM_SYS_LOCALE_DIR, NULL);
      g_free (prgdir);
    }
  else
    {
      localedir = g_strdup (AM_SYS_LOCALE_DIR);
    }

  if (localedir)
    {
      setlocale (LC_ALL, "");
      bindtextdomain (PACKAGE, localedir);
      bind_textdomain_codeset (PACKAGE, "UTF-8");
      textdomain (PACKAGE);
      g_free (localedir);
    }

  gtk_init (&argc, &argv);

  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  gtk_window_set_title (GTK_WINDOW (window), "amedit 0.0.1");
  gtk_window_set_default_size (GTK_WINDOW (window), 600, 400);

  vbox = gtk_vbox_new (FALSE, FALSE);
  gtk_container_add (GTK_CONTAINER (window), vbox);

  editor = wiki_editor_new (NULL);
  gtk_box_pack_start (GTK_BOX (vbox), editor, TRUE, TRUE, 2);

  g_signal_connect (G_OBJECT (window), "destroy-event", G_CALLBACK (amedit_quit_ask), editor);
  g_signal_connect (G_OBJECT (window), "delete-event", G_CALLBACK (amedit_quit_ask), editor);

  gtk_widget_show_all (window);

#ifdef AMBLOG_ENABLE_PROFILER
  ProfilerStart ("amblog.prof");
#endif
  gtk_main ();
#ifdef AMBLOG_ENABLE_PROFILER
  ProfilerStop ();
#endif

  return 0;
}
Exemplo n.º 13
0
int main(int argc, char* argv[]) {
	google::ParseCommandLineFlags(&argc, &argv, true);
	google::InitGoogleLogging(argv[0]);
	LOG(INFO) << "Running...";
	nicopp::DataSet dset(std::move(nicopp::DataSet::Load("compiled/tagf","compiled/vf","compiled/linkf")));
#ifdef DEBUG
	ProfilerStart ("prof.out");
#endif
	/*{
		long t = std::clock();
		bool run = true;
		Graph g;
		g.total_weight = totalLink;
		int degreeTotal = 0;
		for(unsigned int i=0;i<nodes.size();i++){
			nicopp::Node& node = nodes[i];
			degreeTotal += node.neighbors().size();
			g.degrees.emplace_back(degreeTotal);
			for(auto& kv : node.neighbors()){
				g.links.emplace_back(kv.first);
				g.weights.emplace_back(kv.second);
			}
		}
		g.nb_links = g.links.size();
		g.nb_nodes = nodes.size();
		for(;run;){
			int from = g.degrees.size();
			Community c(g, 10, 0);
			LOG(INFO) << g.degrees.size() << " / " << g.links.size() << " / " << g.weights.size() << " <> " << c.size;
			run = c.one_level();
			g = c.partition2graph_binary();
			LOG(INFO) << from << " -> " << g.degrees.size() << " Nodes";
		}
		LOG(INFO) << "Lap: " << (std::clock() - t);
	}*/
	{
		long t = std::clock();
		nicopp::TagGraph graph = dset.searchTag(0, 99999999999, 150000);
		for(int i=0;i<5;i++){
			LOG(INFO) << graph.nodes().size() << " nodes / " << graph.edges() << " edges";
			graph = std::move(graph.nextLevel(4, .0));
		}
		LOG(INFO) << "Lap: " << (std::clock() - t);
		for (auto const& node : graph.nodes()){
			LOG(INFO) << "  Node: " << dset.tag(node.payload().tagId) << " / "<< node.selfLoops() << "/"<<node.degree();
		}
	}
#ifdef DEBUG
	ProfilerStop ();
#endif
	return 0;
}
Exemplo n.º 14
0
int main(int argc, char** argv) {
#ifdef PROFILER
    ProfilerStart("uwsgi_server.prof");
#endif
    stats s;
    tasks::net::acceptor<uwsgi_handler> srv(12345);
    auto tasks = std::vector<tasks::task*>{&srv, &s};
    tasks::dispatcher::instance()->run(tasks);
#ifdef PROFILER
    ProfilerStop();
#endif
    return 0;
}
Exemplo n.º 15
0
Arquivo: t.cpp Projeto: despair1/czk
int main2() {
	ProfilerStart("test2.txt");
	std::ifstream myfile;
	myfile.open("test.txt");
	//myfile<<"wtf?";
	//get_pilot_json("90376921","201407120000",myfile);
	//fclose(fp);
	get_json(myfile);
	std::cout << "!!!Hello World!!!" << std::endl; // prints !!!Hello World!!!
	myfile.close();
	ProfilerStop();
	return 0;
}
Exemplo n.º 16
0
static VALUE
cpuprofiler_stop(VALUE self)
{
  if (!bProfilerRunning)
    return Qfalse;

  bProfilerRunning = Qfalse;
  objprofiler_teardown();
  methprofiler_teardown();
  ProfilerStop();
  ProfilerFlush();

  return Qtrue;
}
Exemplo n.º 17
0
/**
 * returns number of milliseconds spent since _start()
 */
int mypaint_benchmark_end(void)
{
    double time_spent = get_time() - g_start_time;
    g_start_time = 0.0;

    if (profiling_enabled()) {
#ifdef HAVE_GPERFTOOLS
        ProfilerStop();
#else
        fprintf(stderr, "Warning: Not built with gperftools support.\n");
#endif
    }

    assert(time_spent*1000 < INT_MAX);
    return (int)(time_spent*1000);
}
Exemplo n.º 18
0
static void profilerSwitch(int signalNumber) {
  bool static started = false;

  if (!started) {
    if (ProfilerStart(FLAGS_profile_data_file.c_str())) {
      LOG(INFO) << "Profiler started";
    } else {
      LOG(WARNING) << "Can't turn on cpu profiling for "
                   << FLAGS_profile_data_file;
    }
  } else {
    ProfilerStop();
    LOG(INFO) << "Profiler stopped";
  }
  started = !started;
}
Exemplo n.º 19
0
Arquivo: address.c Projeto: 38/glimpse
int main()
{
#ifdef GPROF
	ProfilerStart("/tmp/scanner.prof");
#endif
	glimpse_init();
	Glimpse_TypeAPI_init();
	glimpse_pluginloader_path[0] = ".";
	glimpse_pluginloader_path[1] = "..";
	glimpse_pluginloader_path[2] = NULL;
	glimpse_pluginloader_load_plugin("integer");
	case0();
	glimpse_cleanup();
#ifdef GPROF
	ProfilerStop();
#endif
}
Exemplo n.º 20
0
void ExternalProfiler::stop() {
	if (not this->can_profile) {
		log::log(MSG(err) << "Can not profile: gperftools is missing");
		return;
	}

	if (not this->currently_profiling) {
		log::log(MSG(err) << "Profiler is not currently running");
		return;
	}

	this->currently_profiling = false;
	#if WITH_GPERFTOOLS_PROFILER
	ProfilerStop();
	#endif

	log::log(MSG(info) << "Profiler stopped; data written to " << this->profiling_filename);
}
Exemplo n.º 21
0
int main( int ac, char** av )
{
    try
    {
        #ifdef WIN32
        _setmode( _fileno( stdout ), _O_BINARY );
        #endif
        comma::command_line_options options( ac, av );
        if( options.exists( "--help,-h" ) ) { usage(); }
        csv = comma::csv::options( options, "r,b,e" );
        foreground_threshold = options.value( "--foreground-threshold", 1.0 );
        min_points_per_partition = options.value( "--min-points-per-partition", 1u );
        verbose = options.exists( "--verbose,-v" );
        discard = options.exists( "--discard,-d" );
        output_all = options.exists( "--output-all" );
        ::tbb::filter_t< block_t*, block_t* > partition_filter( ::tbb::filter::serial_in_order, &partition_ );
        ::tbb::filter_t< block_t*, void > write_filter( ::tbb::filter::serial_in_order, &write_block_ );
        #ifdef PROFILE
        ProfilerStart( "points-foreground-partitions.prof" ); {
        #endif
        if( discard )
        {
            bursty_reader.reset( new snark::tbb::bursty_reader< block_t* >( &read_block_bursty_ ) );
            ::tbb::filter_t< void, void > filters = bursty_reader->filter() & partition_filter & write_filter;
            ::tbb::parallel_pipeline( 3, filters ); // while( bursty_reader->wait() ) { ::tbb::parallel_pipeline( 3, filters ); }
            bursty_reader->join();
        }
        else
        {
            ::tbb::filter_t< void, block_t* > read_filter( ::tbb::filter::serial_in_order, &read_block_ );
            ::tbb::filter_t< void, void > filters = read_filter & partition_filter & write_filter;
            ::tbb::parallel_pipeline( 3, filters );
        }
        #ifdef PROFILE
        ProfilerStop(); }
        #endif
        if( is_shutdown ) { std::cerr << "points-foreground-partitions: caught signal" << std::endl; }
        else { std::cerr << "points-foreground-partitions: end of stream" << std::endl; }
        return 0;
    }
    catch( std::exception& ex ) { std::cerr << "points-foreground-partitions: " << ex.what() << std::endl; }
    catch( ... ) { std::cerr << "points-foreground-partitions: unknown exception" << std::endl; }
    return 1;
}
Exemplo n.º 22
0
int main(int argc, const char* argv[]) {
	SDLInterfaceInitData sdlInitData;

	std::vector < std::string > opts;

	for (int i = 0; i < argc; i++) {
		opts.push_back(std::string(argv[i]));
	}

	// running fullscreen is default
	sdlInitData.Fullscreen = false;
	bool runDemoMode = false;
	bool muted = false;
	bool forwardScroll = false;
	bool withIntro = false;
/*
	if (commandline::handleCommandLine(sdlInitData, opts, runDemoMode, muted, forwardScroll, withIntro)
			== false)
		return 0;*/

	DescentFramework f(false, runDemoMode, muted, forwardScroll, withIntro, true);

	f.initRenderEngine(sdlInitData);

	// todo: make this a lot nicer, by templating the FW class
#ifdef USE_PROFILER
	ProfilerStart("GameLoop.perf");
#endif

	f.execute();

#ifdef USE_PROFILER
	ProfilerStop();
#endif

	// done globally here for all used SDL systems;
	SDL_Quit();

	return 0;
}
Exemplo n.º 23
0
bool AdminRequestHandler::handleCPUProfilerRequest(const std::string &cmd,
                                                   Transport *transport) {
  string file = RuntimeOption::ProfilerOutputDir + "/" +
    Process::HostName + "/hphp.prof";

  if (cmd == "prof-cpu-on") {
    if (Util::mkdir(file)) {
      ProfilerStart(file.c_str());
      transport->sendString("OK\n");
    } else {
      transport->sendString("Unable to mkdir for profile data.\n");
    }
    return true;
  }
  if (cmd == "prof-cpu-off") {
    ProfilerStop();
    ProfilerFlush();
    transport->sendString("OK\n");
    return true;
  }
  return false;
}
int main( int argc, char ** argv )
{
#ifdef GOOGLEPROF
	ProfilerStart("test.prof");
#endif

	// parse command line
	if ( argc > 1 ){
		time_to_run_s = atoi(argv[1]);
	}
	if ( argc > 2 ){
		thread_count = atoi(argv[2]);
	}

	printf("SIOX threaded performance test, please run it with and without SIOX instrumentation !\n");
	printf("Parameters: %d threads, %d seconds\n", thread_count, time_to_run_s);

	pthread_barrier_init( & barrier, NULL, thread_count );

	pthread_t thread[thread_count];
	for(int i=0; i < thread_count; i++){
		pthread_create(& thread[i], NULL, threadFunc, (void * restrict) i);
	}

	for(int i=0; i < thread_count; i++){
		void * data;
		pthread_join(thread[i], & data);
	}

	pthread_barrier_destroy( & barrier );

#ifdef GOOGLEPROF
        ProfilerStop("test.prof");
#endif
	return 0;
}
Exemplo n.º 25
0
void bigDictTest() {
    SmartKey::SmartKeyDictionary dictionary(g_settings);

#ifdef HEAP
    HeapProfilerStart("smartkey");
    HeapProfilerDump("period");
#endif

    dictionary.loadSkippedCharsFromFile("/var/tmp/key_skipped");

#ifdef HEAP
    HeapProfilerDump("period");
#endif

    dictionary.loadTermsFromFile("/var/tmp/key_dict_us");
    //dictionary.loadCompiledDictionary("/var/tmp/compiled_key_dict_us");

    //HeapProfilerDump("period");

    dictionary.loadEquivalencesFromFile("/var/tmp/key_equiv");

    //testExactMatchesInFile(dictionary, "/var/tmp/key_dict_us");


     // old test
    /*
    int numInserts = 0;
    dictionary.insert("dork", 69); numInserts++;
    dictionary.insert("door", 67); numInserts++;
    dictionary.insert("doored", 39); numInserts++;
    dictionary.insert("flake", 70); numInserts++;
    dictionary.insert("the", 90); numInserts++;
    dictionary.insert("that", 90); numInserts++;
    dictionary.insert("they", 80); numInserts++;
    dictionary.insert("there", 82); numInserts++;
    dictionary.insert("There's", 81); numInserts++;
    dictionary.insert("at", 90); numInserts++;
    dictionary.insert("it", 91); numInserts++;
    dictionary.insert("for", 69); numInserts++;
    dictionary.insert("attempt", 30); numInserts++;
    dictionary.insert("substantial", 43); numInserts++;
    dictionary.insert("subs", 2); numInserts++;
    dictionary.insert("nonsense", 4); numInserts++;

    dictionary.print();
*/




    allWordsTest(dictionary);

    // small tree insertion test


/*
    std::string there = "there";

    std::string theres = "theres";
    
    std::string therr = "therr";
    
    std::string rhsy = "rhsy";
    
    std::string that = "that";
    std::string that_rgsr = "rgsy";

    dictionary.find(there);
    dictionary.find(therr);
    
    dictionary.find(that);
    dictionary.find(that_rgsr);

    dictionary.find(theres);

    dictionary.find(std::string("fot"));
    dictionary.find(std::string("ot"));
    dictionary.find(std::string("dindrsmrusl"));
  */




/*
    //tiny test
    printf("---- inserting ------\n");
    dictionary.insert("that", 80);
    dictionary.print();
    printf("---- inserting ------\n");
    dictionary.insert("there", 90);
    dictionary.print();
    printf("---- inserting ------\n");
    dictionary.insert("they", 70);
    dictionary.print();
    printf("---- inserting ------\n");
    dictionary.insert("that's", 70);
    dictionary.print();
*/
    /* weird ordering issue
    dictionary.insert("theater", 2);
    dictionary.insert("theaters", 3);
    dictionary.insert("there", 2);
    dictionary.insert("the", 1);
    dictionary.insert("Theme", 4);
    dictionary.insert("Thematic", 1);
    dictionary.insert("Th", 10);
    dictionary.insert("those", 1);
     */

    //dictionary.print();
    //test(dictionary, "there", "there");
#ifdef HEAP
    ProfilerStart("smartkeyCpu");
#endif

    /*
    test(dictionary, "tha", "that");
    test(dictionary, "rgru", "they");
    test(dictionary, "subs", "sub's");
    test(dictionary, "substanti", "substantial");
    test(dictionary, "mimdrbdr", "nonsense");
*/
#ifdef HEAP
    ProfilerStop();
#endif

    //dictionary.insert("the", 100000);



    int size = 0;
    int numOfSize = -1;

    printf("%s: number of nodes: %d\n", __FUNCTION__, dictionary.getNodeCount());

    while (numOfSize != 0) {
        int capacity = 0;
        numOfSize = dictionary.singlesCounter(size, capacity);
        printf("%s: number of child maps with only %d child: %d\n", __FUNCTION__, size, numOfSize);
        size++;
    }

    printf("%s: num removable nodes: %d\n", __FUNCTION__, dictionary.numRemovableNodes());



    printf("%s: node size: %d\n", __FUNCTION__,
            sizeof(SmartKeyNode));
}
Exemplo n.º 26
0
void StopProfiling::executePlanOperation() {
#ifdef HYRISE_USE_GOOGLE_PROFILER
  ProfilerStop();
#endif
  output = input;
}
Exemplo n.º 27
0
int
main(int argc, char *argv[]) {
	isc_result_t result;
#ifdef HAVE_LIBSCF
	char *instance = NULL;
#endif

#ifdef HAVE_GPERFTOOLS_PROFILER
	(void) ProfilerStart(NULL);
#endif

	/*
	 * Record version in core image.
	 * strings named.core | grep "named version:"
	 */
	strlcat(version,
#if defined(NO_VERSION_DATE) || !defined(__DATE__)
		"named version: BIND " VERSION " <" SRCID ">",
#else
		"named version: BIND " VERSION " <" SRCID "> (" __DATE__ ")",
#endif
		sizeof(version));
	result = isc_file_progname(*argv, program_name, sizeof(program_name));
	if (result != ISC_R_SUCCESS)
		ns_main_earlyfatal("program name too long");

	if (strcmp(program_name, "lwresd") == 0)
		ns_g_lwresdonly = ISC_TRUE;

	if (result != ISC_R_SUCCESS)
		ns_main_earlyfatal("failed to build internal symbol table");

	isc_assertion_setcallback(assertion_failed);
	isc_error_setfatal(library_fatal_error);
	isc_error_setunexpected(library_unexpected_error);

	ns_os_init(program_name);

	dns_result_register();
	dst_result_register();
	isccc_result_register();
#ifdef PKCS11CRYPTO
	pk11_result_register();
#endif

	parse_command_line(argc, argv);

	pfilter_open();

	/*
	 * Warn about common configuration error.
	 */
	if (ns_g_chrootdir != NULL) {
		int len = strlen(ns_g_chrootdir);
		if (strncmp(ns_g_chrootdir, ns_g_conffile, len) == 0 &&
		    (ns_g_conffile[len] == '/' || ns_g_conffile[len] == '\\'))
			ns_main_earlywarning("config filename (-c %s) contains "
					     "chroot path (-t %s)",
					     ns_g_conffile, ns_g_chrootdir);
	}

	result = isc_mem_create(0, 0, &ns_g_mctx);
	if (result != ISC_R_SUCCESS)
		ns_main_earlyfatal("isc_mem_create() failed: %s",
				   isc_result_totext(result));
	isc_mem_setname(ns_g_mctx, "main", NULL);

	setup();

	/*
	 * Start things running and then wait for a shutdown request
	 * or reload.
	 */
	do {
		result = isc_app_run();

		if (result == ISC_R_RELOAD) {
			ns_server_reloadwanted(ns_g_server);
		} else if (result != ISC_R_SUCCESS) {
			UNEXPECTED_ERROR(__FILE__, __LINE__,
					 "isc_app_run(): %s",
					 isc_result_totext(result));
			/*
			 * Force exit.
			 */
			result = ISC_R_SUCCESS;
		}
	} while (result != ISC_R_SUCCESS);

#ifdef HAVE_LIBSCF
	if (ns_smf_want_disable == 1) {
		result = ns_smf_get_instance(&instance, 1, ns_g_mctx);
		if (result == ISC_R_SUCCESS && instance != NULL) {
			if (smf_disable_instance(instance, 0) != 0)
				UNEXPECTED_ERROR(__FILE__, __LINE__,
						 "smf_disable_instance() "
						 "failed for %s : %s",
						 instance,
						 scf_strerror(scf_error()));
		}
		if (instance != NULL)
			isc_mem_free(ns_g_mctx, instance);
	}
#endif /* HAVE_LIBSCF */

	cleanup();

	if (want_stats) {
		isc_mem_stats(ns_g_mctx, stdout);
		isc_mutex_stats(stdout);
	}

	if (ns_g_memstatistics && memstats != NULL) {
		FILE *fp = NULL;
		result = isc_stdio_open(memstats, "w", &fp);
		if (result == ISC_R_SUCCESS) {
			isc_mem_stats(ns_g_mctx, fp);
			isc_mutex_stats(fp);
			isc_stdio_close(fp);
		}
	}
	isc_mem_destroy(&ns_g_mctx);
	isc_mem_checkdestroyed(stderr);

	ns_main_setmemstats(NULL);

	isc_app_finish();

	ns_os_closedevnull();

	ns_os_shutdown();

#ifdef HAVE_GPERFTOOLS_PROFILER
	ProfilerStop();
#endif

	return (0);
}
Exemplo n.º 28
0
void
tarjan_run (run_t *run, wctx_t *ctx)
{
    alg_local_t        *loc        = ctx->local;
    raw_data_t         *addr;
    raw_data_t          state_data;
    bool                on_stack;
    hash32_t            hash;

#ifdef HAVE_PROFILER
    Warning (info, "Using the profiler");
    ProfilerStart ("tarjan.perf");
#endif

#ifdef SEARCH_COMPLETE_GRAPH
    int              init_state = dlopen_get_worker_initial_state (ctx->id, W);
    int              inits      = 0;

    // loop until every state of the graph has been visited
    while ( 1 )
    {
        inits ++;
        // use loc->target as a dummy for the initial state
        loc->target->ref = init_state;
#endif

    tarjan_init (ctx);
    
    // continue until we are done exploring the graph
    while ( !run_is_stopped (run) ) {

        state_data = dfs_stack_top (loc->search_stack);

        if (state_data != NULL) {
            // there is a state on the current stackframe ==> explore it

            state_info_deserialize (ctx->state, state_data);

            // pop the state and continue if it is part of a completed SCC
            if (state_store_has_color (ctx->state->ref, SCC_STATE, 0)) {
                dfs_stack_pop (loc->search_stack);
                continue;
            }

            hash     = ref_hash (ctx->state->ref);
            on_stack = fset_find (loc->visited_states, &hash,
                                  &ctx->state->ref, (void **) &addr, true);

            if (!on_stack) {
                // unseen state ==> initialize and explore

                HREassert (loc->cnt.tarjan_counter != UINT32_MAX);
                loc->cnt.tarjan_counter ++;
                loc->state_tarjan.index   = loc->cnt.tarjan_counter;
                loc->state_tarjan.lowlink = loc->cnt.tarjan_counter;

                // point visited_states data to stack
                *addr = state_data;

                explore_state (ctx);

                state_info_serialize (ctx->state, state_data);

            } else {
                // previously visited state ==> update parent
                // NB: state is on tarjan_stack

                state_info_deserialize (ctx->state, *addr);
                update_parent (ctx, loc->state_tarjan.lowlink);
                dfs_stack_pop (loc->search_stack);
            }

        } else {
            // there is no state on the current stackframe ==> backtrack

            // we are done if we backtrack from the initial state
            if (0 == dfs_stack_nframes (loc->search_stack))
                break;

            // leave the stackframe
            dfs_stack_leave (loc->search_stack);
            ctx->counters->level_cur--;

            // retrieve the parent state from search_stack (to be removed)
            state_data = dfs_stack_top (loc->search_stack);
            state_info_deserialize (ctx->state, state_data);

            Debug ("Backtracking %zu (%d, %d)", ctx->state->ref,
                   loc->state_tarjan.index, loc->state_tarjan.lowlink);

            if (loc->state_tarjan.index == loc->state_tarjan.lowlink) {
                // index == lowlink ==> root of the SCC ==> report the SCC
                pop_scc (ctx, ctx->state->ref, loc->state_tarjan.lowlink);

            } else {
                // lowlink < index ==> LIVE SCC ==> move to tarjan_stack
                move_tarjan (ctx, ctx->state, state_data);
                update_parent (ctx, loc->state_tarjan.lowlink);
            }

            dfs_stack_pop (loc->search_stack);
        }
    }

#ifdef SEARCH_COMPLETE_GRAPH
        init_state = dlopen_get_new_initial_state (init_state);
        if (init_state == -1) {
            Warning(info, "Number of inits : %d", inits);
            break;
        }
    }
#endif

#ifdef HAVE_PROFILER
    Warning(info, "Done profiling");
    ProfilerStop();
#endif

    if (!run_is_stopped(run) && dfs_stack_size(loc->tarjan_stack) != 0)
        Warning (info, "Tarjan stack not empty: %zu (stack %zu)",
                 dfs_stack_size(loc->tarjan_stack),
                 dfs_stack_size(loc->search_stack));
    if (!run_is_stopped(run) && fset_count(loc->visited_states) != 0)
        Warning (info, "Stack-set not empty: %zu",
                 fset_count(loc->visited_states));
}
Exemplo n.º 29
0
int main(int argc, const char *argv[])
{
	fake * fk = newfake();

	// 解析参数
	int parseret = parsearg(fk, argc, argv);
	if (parseret != 0)
	{
		return parseret;
	}

	if (g_iscompiled)
	{
		fksetargv(fk, argc - 1, argv + 1);
	}
	else
	{
		fksetargv(fk, argc - 2, argv + 2);
	}
	fkopenalllib(fk);
	fkseterrorfunc(fk, error_log);

	// for test
	fkreg(fk, "test_cfunc1", test_cfunc1);
	fkreg(fk, "new_test_class1", new_test_class1);
	fkreg(fk, "new_test_class2", new_test_class2);
	fkreg(fk, "delete_test_class1", delete_test_class1);
	fkreg(fk, "delete_test_class2", delete_test_class2);
	fkreg(fk, "test_memfunc1", &test_class1::test_memfunc1); 
	fkreg(fk, "test_memfunc1", &test_class2::test_memfunc1); 
	fkreg(fk, "test_memfunc2", &test_class2::test_memfunc2); 

	// 编译后文件
	if (g_iscompiled)
	{
		// 打开自己
		char * selftmpbuf = 0;
		int selfsize = 0;
		if (!readfile(g_selfname, 0, selftmpbuf, selfsize))
		{
			return -1;
		}

		int startpos = 0;
		int size = 0;
		memcpy(&startpos, g_replacebuff, sizeof(startpos));
		memcpy(&size, g_replacebuff + 4, sizeof(size));

		if (fkloadfunc(fk, selftmpbuf + startpos, size) == -1)
		{
			printf("load func fail\n");
			return -1;
		}

		free(selftmpbuf);
	}
	// 解析文件
	else if (!g_isload)
	{
		fkparse(fk, argv[1]);
		if (fkerror(fk))
		{
			return -1;
		}
	}
	// 读文件
	else
	{
		// 读文件
		char * tmpbuf = 0;
		int size = 0;
		if (!readfile(argv[1], 0, tmpbuf, size))
		{
			return -1;
		}

		if (fkloadfunc(fk, tmpbuf, size) == -1)
		{
			printf("load func fail\n");
			return -1;
		}

		free(tmpbuf);
		printf("load from %s ok, size %d\n", argv[1], size);
	}

	// 存文件
	if (g_issave)
	{
		int tmpsize = 1024 * 1024;
		char * tmpbuf = (char *)malloc(tmpsize);
		int size = fksavefunc(fk, tmpbuf, tmpsize);
		if (size == -1)
		{
			printf("save func fail\n");
			return -1;
		}

		const char * filename = "fake.bin";
		if (!writefile(filename, tmpbuf, size))
		{
			return -1;
		}
		free(tmpbuf);
		
		printf("save to %s ok, size %d\n", filename, size);
		
		return 0;
	}

	// 编译到一起
	if (g_iscompile)
	{
		int tmpsize = 1024 * 1024;
		char * tmpbuf = (char *)malloc(tmpsize);
		int size = fksavefunc(fk, tmpbuf, tmpsize);
		if (size == -1)
		{
			printf("compile func fail\n");
			return -1;
		}

		// 打开自己
		char * selftmpbuf = 0;
		int selfsize = 0;
		if (!readfile(g_selfname, size, selftmpbuf, selfsize))
		{
			return -1;
		}

		// 替换内存中的字符串
		bool isfind = false;
		for (int i = 0; i < selfsize; i++)
		{
			if (memcmp(selftmpbuf + i, g_replacebuff, strlen(g_replacebuff)) == 0)
			{
				memcpy(selftmpbuf + i, &selfsize, sizeof(selfsize));
				memcpy(selftmpbuf + i + 4, &size, sizeof(size));
				isfind = true;
				break;
			}
		}
		if (!isfind)
		{
			printf("replace %s pos fail\n", argv[0]);
			return -1;
		}

		// 复制后面的
		memcpy(selftmpbuf + selfsize, tmpbuf, size);
		free(tmpbuf);

		// 输出
		const char * filename = "out.exe";
		if (!writefile(filename, selftmpbuf, selfsize + size))
		{
			return -1;
		}
		free(selftmpbuf);

		printf("compile to %s ok, size %d\n", filename, selfsize + size);

		return 0;
	}

#ifndef WIN32
	if (g_isopengoogleprofile)
	{
		ProfilerStart("fake.prof");
	}
#endif

	uint32_t begintime = time(0);
	int fkret = 0;

	// run
	for (int i = 0; i < g_testnum; i++)
	{
		if (!g_isopenjit)
		{
			if (g_isstep)
			{
				fkret = fkdebugrun<int>(fk, "main");
			}
			else
			{
				fkret = fkrun<int>(fk, "main");
			}
		}
		else
		{
			fkret = fkrunjit<int>(fk, "main");
		}
	}
	
	uint32_t endtime = time(0);

#ifndef WIN32
	if (g_isopengoogleprofile)
	{
		ProfilerStop();
	}
#endif

	if (fkerror(fk))
	{
		return -1;
	}

	if (g_isopenprofile)
	{
		printf("\n%s", fkdumpprofile(fk));
	}

	if (g_isprintoutput)
	{
		printf("main return : %d, use time %d\n", fkret, endtime - begintime);
	}

	delfake(fk);

	return 0;
}
Exemplo n.º 30
0
void PProfService::profile(
    ::google::protobuf::RpcController* controller_base,
    const ::brpc::ProfileRequest* /*request*/,
    ::brpc::ProfileResponse* /*response*/,
    ::google::protobuf::Closure* done) {
    ClosureGuard done_guard(done);
    Controller* cntl = static_cast<Controller*>(controller_base);
    cntl->http_response().set_content_type("text/plain");
    if ((void*)ProfilerStart == NULL || (void*)ProfilerStop == NULL) {
        cntl->SetFailed(ENOMETHOD, "%s, to enable cpu profiler, check out "
                        "docs/cn/cpu_profiler.md",
                        berror(ENOMETHOD));
        return;
    }    
    int sleep_sec = ReadSeconds(cntl);
    if (sleep_sec <= 0) {
        if (!cntl->Failed()) {
            cntl->SetFailed(EINVAL, "You have to specify ?seconds=N. If you're "
                            "using pprof, add --seconds=N");
        }
        return;
    }
    // Log requester
    std::ostringstream client_info;
    client_info << cntl->remote_side();
    if (cntl->auth_context()) {
        client_info << "(auth=" << cntl->auth_context()->user() << ')';
    } else {
        client_info << "(no auth)";
    }
    LOG(INFO) << client_info.str() << " requests for cpu profile for "
              << sleep_sec << " seconds";

    char prof_name[256];
    if (MakeProfName(PROFILING_CPU, prof_name, sizeof(prof_name)) != 0) {
        cntl->SetFailed(errno, "Fail to create .prof file, %s", berror());
        return;
    }
    butil::File::Error error;
    const butil::FilePath dir = butil::FilePath(prof_name).DirName();
    if (!butil::CreateDirectoryAndGetError(dir, &error)) {
        cntl->SetFailed(EPERM, "Fail to create directory=`%s'",dir.value().c_str());
        return;
    }
    if (!ProfilerStart(prof_name)) {
        cntl->SetFailed(EAGAIN, "Another profiler is running, try again later");
        return;
    }
    if (bthread_usleep(sleep_sec * 1000000L) != 0) {
        PLOG(WARNING) << "Profiling has been interrupted";
    }
    ProfilerStop();

    butil::fd_guard fd(open(prof_name, O_RDONLY));
    if (fd < 0) {
        cntl->SetFailed(ENOENT, "Fail to open %s", prof_name);
        return;
    }
    butil::IOPortal portal;
    portal.append_from_file_descriptor(fd, ULONG_MAX);
    cntl->response_attachment().swap(portal);
}