/** * @brief retrieves the cpu usage statistics for the domain * @return true if the cpu statistic was retrieved without error, otherwise false */ bool Domain::cpustats() { unsigned int nparams = cpu_count(); virTypedParameterPtr params = static_cast<virTypedParameterPtr>( calloc(nparams, sizeof(virTypedParameter))); int start_cpu = 0; unsigned int ncpus = cpu_count(); unsigned int flags = 0; return (virDomainGetCPUStats(m_domain, params, nparams, start_cpu, ncpus, flags) == 0); }
static int do_top(virConnectPtr conn, const char *dom_name, unsigned int milliseconds) { int ret = -1; virDomainPtr dom; int max_id = 0; int nparams = 0, then_nparams = 0, now_nparams = 0; virTypedParameterPtr then_params = NULL, now_params = NULL; /* Lookup the domain */ if (!(dom = virDomainLookupByName(conn, dom_name))) { ERROR("Unable to find domain '%s'", dom_name); goto cleanup; } /* and see how many vCPUs can we fetch stats for */ if ((max_id = virDomainGetCPUStats(dom, NULL, 0, 0, 0, 0)) < 0) { ERROR("Unable to get cpu stats"); goto cleanup; } /* how many stats can we get for a vCPU? */ if ((nparams = virDomainGetCPUStats(dom, NULL, 0, 0, 1, 0)) < 0) { ERROR("Unable to get cpu stats"); goto cleanup; } if (!(now_params = calloc(nparams * max_id, sizeof(*now_params))) || !(then_params = calloc(nparams * max_id, sizeof(*then_params)))) { ERROR("Unable to allocate memory"); goto cleanup; } /* The ideal program would use sigaction to set this handler, but * this way is portable to mingw. */ signal(SIGTERM, stop); signal(SIGINT, stop); run_top = true; while (run_top) { struct timeval then, now; /* Get current time */ if (gettimeofday(&then, NULL) < 0) { ERROR("unable to get time"); goto cleanup; } /* And current stats */ if ((then_nparams = virDomainGetCPUStats(dom, then_params, nparams, 0, max_id, 0)) < 0) { ERROR("Unable to get cpu stats"); goto cleanup; } /* Now sleep some time */ usleep(milliseconds * 1000); /* usleep expects microseconds */ /* And get current time */ if (gettimeofday(&now, NULL) < 0) { ERROR("unable to get time"); goto cleanup; } /* And current stats */ if ((now_nparams = virDomainGetCPUStats(dom, now_params, nparams, 0, max_id, 0)) < 0) { ERROR("Unable to get cpu stats"); goto cleanup; } print_cpu_usage(0, max_id, then.tv_sec * 1000000 + then.tv_usec, then_params, then_nparams, now.tv_sec * 1000000 + now.tv_usec, now_params, now_nparams); virTypedParamsClear(now_params, now_nparams * max_id); virTypedParamsClear(then_params, then_nparams * max_id); } ret = 0; cleanup: virTypedParamsFree(now_params, nparams * max_id); virTypedParamsFree(then_params, nparams * max_id); if (dom) virDomainFree(dom); return ret; }