How to get CPU usage with different states in IOS for example
1.Idle
2.Running a user space
3.Running the kernel/system
The CPU usage example such as this provide total CPU usage only like below.How can I check the different states within the usage?
Any help?
A general usage example available mostly is like below :
- (NSString *)cpuUsage
{
kern_return_t kr;
task_info_data_t tinfo;
mach_msg_type_number_t task_info_count;
task_info_count = TASK_INFO_MAX;
kr = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)tinfo, &task_info_count);
if (kr != KERN_SUCCESS)
{
return #"NA";
}
task_basic_info_t basic_info;
thread_array_t thread_list;
mach_msg_type_number_t thread_count;
thread_info_data_t thinfo;
mach_msg_type_number_t thread_info_count;
thread_basic_info_t basic_info_th;
uint32_t stat_thread = 0; // Mach threads
basic_info = (task_basic_info_t)tinfo;
// get threads in the task
kr = task_threads(mach_task_self(), &thread_list, &thread_count);
if (kr != KERN_SUCCESS)
{
return #"NA";
}
if (thread_count > 0)
stat_thread += thread_count;
long tot_sec = 0;
long tot_usec = 0;
float tot_cpu = 0;
int j;
for (j = 0; j < thread_count; j++)
{
thread_info_count = THREAD_INFO_MAX;
kr = thread_info(thread_list[j], THREAD_BASIC_INFO,
(thread_info_t)thinfo, &thread_info_count);
if (kr != KERN_SUCCESS)
{
return nil;
}
basic_info_th = (thread_basic_info_t)thinfo;
if (!(basic_info_th->flags & TH_FLAGS_IDLE))
{
//This is 0
tot_sec = tot_sec + basic_info_th->user_time.seconds + basic_info_th->system_time.seconds;
//This is 0
tot_usec = tot_usec + basic_info_th->system_time.microseconds + basic_info_th->system_time.microseconds;
//This is total
tot_cpu = tot_cpu + basic_info_th->cpu_usage / (float)TH_USAGE_SCALE * 100.0;
}
} // for each thread
kr = vm_deallocate(mach_task_self(), (vm_offset_t)thread_list, thread_count * sizeof(thread_t));
assert(kr == KERN_SUCCESS);
return [NSString stringWithFormat:#"%.2f",tot_cpu];
}
Edit
I did try the sample mentioned .here but the kernel/system reading always return 0 on actual device.
Is it correct? I am not sure.
Try this Objective-C class;
Get current App CPU usage SystemMonitor.cpuUsage()
Get total CPU usage SystemMonitor.usage()
SystemMonitor.h
#ifndef SystemMonitor_h
#define SystemMonitor_h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
typedef struct {
unsigned int system;
unsigned int user;
unsigned int nice;
unsigned int idle;
} CPUUsage;
#interface SystemMonitor: NSObject
+ (CPUUsage)cpuUsage;
+ (CGFloat)appCpuUsage;
#end
#endif /* SystemMonitor_h */
SystemMonitor.m
#import <Foundation/Foundation.h>
#import "SystemMonitor.h"
#import <sys/sysctl.h>
#import <mach/mach.h>
#import <sys/stat.h>
#implementation SystemMonitor
+ (CPUUsage)cpuUsage {
kern_return_t kr;
mach_msg_type_number_t count;
static host_cpu_load_info_data_t previous_info = {0, 0, 0, 0};
host_cpu_load_info_data_t info;
CPUUsage usage = {0, 0, 0, 1};
count = HOST_CPU_LOAD_INFO_COUNT;
kr = host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO, (host_info_t)&info, &count);
if (kr != KERN_SUCCESS) {
return usage;
}
natural_t user = info.cpu_ticks[CPU_STATE_USER] - previous_info.cpu_ticks[CPU_STATE_USER];
natural_t nice = info.cpu_ticks[CPU_STATE_NICE] - previous_info.cpu_ticks[CPU_STATE_NICE];
natural_t system = info.cpu_ticks[CPU_STATE_SYSTEM] - previous_info.cpu_ticks[CPU_STATE_SYSTEM];
natural_t idle = info.cpu_ticks[CPU_STATE_IDLE] - previous_info.cpu_ticks[CPU_STATE_IDLE];
//natural_t total = user + nice + system + idle;
previous_info = info;
usage.user = user;
usage.system = system;
usage.nice = nice;
usage.idle = idle;
//return (user + nice + system) * 100.0 / total;
return usage;
}
static NSUInteger const kMaxPercent = 100;
+ (CGFloat)appCpuUsage {
kern_return_t kr;
task_info_data_t tinfo;
mach_msg_type_number_t task_info_count;
task_info_count = TASK_INFO_MAX;
kr = task_info(mach_task_self(), MACH_TASK_BASIC_INFO, (task_info_t)tinfo, &task_info_count);
if (kr != KERN_SUCCESS) {
return -1;
}
thread_array_t thread_list;
mach_msg_type_number_t thread_count;
thread_info_data_t thinfo;
mach_msg_type_number_t thread_info_count;
thread_basic_info_t basic_info_th;
// get threads in the task
kr = task_threads(mach_task_self(), &thread_list, &thread_count);
if (kr != KERN_SUCCESS) {
return -1;
}
long total_time = 0;
long total_userTime = 0;
CGFloat total_cpu = 0;
int j;
// for each thread
for (j = 0; j < (int)thread_count; j++) {
thread_info_count = THREAD_INFO_MAX;
kr = thread_info(thread_list[j], THREAD_BASIC_INFO,
(thread_info_t)thinfo, &thread_info_count);
if (kr != KERN_SUCCESS) {
return -1;
}
basic_info_th = (thread_basic_info_t)thinfo;
if (!(basic_info_th->flags & TH_FLAGS_IDLE)) {
total_time = total_time + basic_info_th->user_time.seconds + basic_info_th->system_time.seconds;
total_userTime = total_userTime + basic_info_th->user_time.microseconds + basic_info_th->system_time.microseconds;
total_cpu = total_cpu + basic_info_th->cpu_usage / (float)TH_USAGE_SCALE * kMaxPercent;
}
}
kr = vm_deallocate(mach_task_self(), (vm_offset_t)thread_list, thread_count * sizeof(thread_t));
assert(kr == KERN_SUCCESS);
return total_cpu;
}
#end
Related
The EA has no bugs but it doesn't really do what I expected it to do, it should, for example, sell from var_30[i], put a tp at var_2[i] and sl at var_30[i]+(var_30[i]-var_2[i])/2 or buy from var_20[i], put a tp at var_3[i] and sl at var_20[i]+(var_20[i]-var_3[i])/2
I tried to modify it several times but in the end, after using the strategy tester feature the graph always goes to 0, which shouldn't.
Here is the code:
#property description "Price Border strategy expert advisor by Razvan"
//--- Inputs
extern double Lots =1;
extern double MaximumRisk =2;
extern string TimeFrame = "All tf";
extern int HalfLength = 61;
extern int Price = 0;
extern double ATRMultiplier = 1.6;
extern double ATRMultiplier1 = 3.6;
extern int ATRPeriod = 480;
extern bool Interpolate = TRUE;
extern bool alertsOn = TRUE;
extern bool alertsOnCurrent = FALSE;
extern bool alertsOnHighLow = TRUE;
extern bool alertsMessage = FALSE;
extern bool alertsSound = TRUE;
extern bool alertsEmail = FALSE;
double var_1[];
double var_2[];
double var_3[];
double var_4[];
double var_20[];
double var_30[];
string string_1;
bool bool_1;
bool bool_2;
int var_5;
string string_2 = "nothing";
datetime Gt_176;
string string_3[] = {"M1", "M5", "M15", "M30", "H1", "H4", "D1", "W1", "MN"};
int var_6[] = {1, 5, 15, 30, 60, 240, 1440, 10080, 43200};
int res;
// init function
int init() {
string str_4[256];
for (int i = 0; i < 256; i++) str_4[i] = CharToStr(i);
int var_7 = StrToInteger(str_4[67] + str_4[111] + str_4[112] + str_4[121] + str_4[32] + str_4[82]+ str_4[105] + str_4[103] + str_4[104] + str_4[116] + str_4[32] +
str_4[169] + str_4[32] + str_4[75] + str_4[97] + str_4[122] + str_4[97] + str_4[111] + str_4[111] + str_4[32] + str_4[50] + str_4[48] + str_4[49] + str_4[49] + str_4[32]);
IndicatorBuffers(4);
HalfLength = MathMax(HalfLength, 1);
SetIndexBuffer(0, var_1);
SetIndexDrawBegin(0, HalfLength);
SetIndexBuffer(1, var_2);
SetIndexDrawBegin(1, HalfLength);
SetIndexBuffer(2, var_3);
SetIndexDrawBegin(2, HalfLength);
SetIndexBuffer(3, var_4);
string_1 = WindowExpertName();
bool_2 = TimeFrame == "returnBars";
if (bool_2) return (0);
bool_1 = TimeFrame == "calculateValue";
if (bool_1) return (0);
var_5 = func_3(TimeFrame);
IndicatorShortName(func_0(var_5) + " TMA bands )" + HalfLength + ")");
return (0);
}
// deinit function
int deinit() {
return (0);
}
// start function
int start() {
int var_7;
double double_1;
double double_2;
double double_3;
double double_31;
int var_8;
int var_9;
int var_10 = IndicatorCounted();
if (var_10 < 0) return (-1);
if (var_10 > 0) var_10--;
int var_11 = MathMin(Bars - 1, Bars - var_10 + HalfLength);
if (bool_2) {
var_1[0] = var_11 + 1;
return (0);
}
if (bool_1 || var_5 == Period()) {
for (int i = var_11; i >= 0; i--) {
double_1 = (HalfLength + 1) * iMA(NULL, 0, 1, 0, MODE_SMA, Price, i);
double_2 = HalfLength + 1;
var_7 = 1;
for (int var_12 = HalfLength; var_7 <= HalfLength; var_12--) {
double_1 += var_12 * iMA(NULL, 0, 1, 0, MODE_SMA, Price, i + var_7);
double_2 += var_12;
if (var_7 <= i) {
double_1 += var_12 * iMA(NULL, 0, 1, 0, MODE_SMA, Price, i - var_7);
double_2 += var_12;
}
var_7++;
}
double_3 = iATR(NULL, 0, ATRPeriod, i + 10) * ATRMultiplier;
double_31 = iATR(NULL, 0, ATRPeriod, i + 10) * ATRMultiplier1;
var_1[i] = double_1 / double_2;
var_2[i] = var_1[i] + double_3;
var_20[i] = var_1[i] + double_31;
var_30[i] = var_1[i] - double_31;
var_3[i] = var_1[i] - double_3;
var_4[i] = 0;
if (alertsOnHighLow) {
if (High[i] > var_2[i]) var_4[i] = 1;
if (Low[i] < var_3[i]) var_4[i] = -1;
} else {
if (Close[i] > var_2[i]) var_4[i] = 1;
if (Close[i] < var_3[i]) var_4[i] = -1;
}
}
if (!(!bool_1)) return (0);
func_1();
return (0);
}
var_11 = MathMax(var_11, MathMin(Bars - 1, iCustom(NULL, var_5, string_1, "returnBars", 0, 0) * var_5 / Period()));
for (i = var_11; i >= 0; i--) {
var_8 = iBarShift(NULL, var_5, Time[i]);
var_1[i] = iCustom(NULL, var_5, string_1, "calculateTma", HalfLength, Price, ATRMultiplier, ATRPeriod, 0, var_8);
var_2[i] = iCustom(NULL, var_5, string_1, "calculateTma", HalfLength, Price, ATRMultiplier, ATRPeriod, 1, var_8);
var_3[i] = iCustom(NULL, var_5, string_1, "calculateTma", HalfLength, Price, ATRMultiplier, ATRPeriod, 2, var_8);
var_4[i] = iCustom(NULL, var_5, string_1, "calculateTma", HalfLength, Price, ATRMultiplier, ATRPeriod, 3, var_8);
if (var_5 <= Period() || var_8 == iBarShift(NULL, var_5, Time[i - 1])) continue;
if (Interpolate) {
var_9 = iTime(NULL, var_5, var_8);
for (int var_14 = 1; i + var_14 < Bars && Time[i + var_14] >= var_9; var_14++) {
}
for (var_14 = 1; var_12 < var_14; var_12++) {
var_1[i + var_12] = var_1[i] + (var_1[i + var_14] - var_1[i]) * var_12 / var_14;
var_2[i + var_12] = var_2[i] + (var_2[i + var_14] - var_2[i]) * var_12 / var_14;
var_3[i + var_12] = var_3[i] + (var_3[i + var_14] - var_3[i]) * var_12 / var_14;
}
}
}
func_1();
return (0);
}
// function1
void func_1() {
int var_10;
if (alertsOn) {
if (alertsOnCurrent) var_10 = 0;
else var_10 = 1;
var_10 = iBarShift(NULL, 0, iTime(NULL, var_5, var_10));
if (var_4[var_10] != var_4[var_10 + 1]) {
if (var_4[var_10] == 1.0) func_4(var_10, "up");
if (var_4[var_10] == -1.0) func_4(var_10, "down");
}
}
}
// function4
void func_4(int var_12, string str_5) {
string str_6;
if (string_2 != str_5 || Gt_176 != Time[var_12]) {
string_2 = str_5;
Gt_176 = Time[var_12];
str_6 = StringConcatenate(Symbol(), " at ", TimeToStr(TimeLocal(), TIME_SECONDS), " " + func_0(var_5) + " TMA bands price penetrated ", str_5, " band");
if (alertsMessage) Alert(str_6);
if (alertsEmail) SendMail(StringConcatenate(Symbol(), "TMA bands "), str_6);
if (alertsSound) PlaySound("alert2.wav");
}
}
// function3
int func_3(string str_7) {
str_7 = func_2(str_7);
for (int var_7 = ArraySize(var_6) - 1; var_7 >= 0; var_7--)
if (str_7 == string_3[var_7] || str_7 == "" + var_6[var_7]) return (MathMax(var_6[var_7], Period()));
return (Period());
}
// function0
string func_0(int var_12) {
for (int i = ArraySize(var_6) - 1; i >= 0; i--)
if (var_12 == var_6[i]) return (string_3[i]);
return ("");
}
// function2
string func_2(string str_7) {
int var_13;
string str_8 = str_7;
for (int var_11 = StringLen(str_7) - 1; var_11 >= 0; var_11--) {
var_13 = StringGetChar(str_8, var_11);
if ((var_13 > '`' && var_13 < '{') || (var_13 > 'ß' && var_13 < 256)) str_8 = StringSetChar(str_8, var_11, var_13 - 32);
else
if (var_13 > -33 && var_13 < 0) str_8 = StringSetChar(str_8, var_11, var_13 + 224);
}
return (str_8);
}
//+------------------------------------------------------------------+
//| Calculate open positions |
//+------------------------------------------------------------------+
int CalculateCurrentOrders(string symbol)
{
int buys=0,sells=0;
//---
for(int i=0;i<OrdersTotal();i++)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
if(OrderSymbol()==Symbol())
{
if(OrderType()==OP_BUY) buys++;
if(OrderType()==OP_SELL) sells++;
}
}
//--- return orders volume
if(buys>0) return(buys);
else return(-sells);
}
//+------------------------------------------------------------------+
//| Calculate optimal lot size |
//+------------------------------------------------------------------+
double LotsOptimized()
{
double lot=Lots;
if(lot<0.1) lot=0.1;
return(lot);
}
//+------------------------------------------------------------------+
//| Check for open order conditions |
//+------------------------------------------------------------------+
void CheckForOpen()
{ int var_10 = IndicatorCounted();
int var_11 = MathMin(Bars - 1, Bars - var_10 + HalfLength);
for (int i = var_11; i >= 0; i--)
{if(High[i] > var_30[i] || Close[i] > var_30[i])
{
res=OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,30,var_30[i]+(var_30[i]- var_2[i])/2,var_2[i],"",0,Red); //Symbol(),OP_BUY,1,price,3,stoploss,takeprofit,"My order",16384,0,clrGreen
return;
}
//--- buy conditions
else if(Low[i] < var_20[i] || Close[i] < var_20[i])
{
res=OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,30,var_20[i]+(var_20[i]-var_3[i])/2,var_3[i],"",0,Green);
return;
}}
//---
}
//+------------------------------------------------------------------+
//| Check for close order conditions |
//+------------------------------------------------------------------+
void CheckForClose()
{
if(Volume[0]>0.1) return;
for(int i=0;i<OrdersTotal();i++)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
if(OrderSymbol()!=Symbol()) continue;
//--- check order type
if(OrderType()==OP_BUY)
{
if(High[i] >= var_3[i] || Low[i] <= var_30[i]+(var_30[i]-var_2[i])/2)
{
if(!OrderClose(OrderTicket(),OrderLots(),Bid,30,White))
Print("OrderClose error ",GetLastError());
}
break;
}
if(OrderType()==OP_SELL)
{
if(Low[i] <= var_2[i] || High[i] >= var_20[i]+(var_20[i]-var_3[i])/2)
{
if(!OrderClose(OrderTicket(),OrderLots(),Ask,30,White))
Print("OrderClose error ",GetLastError());
}
break;
}
}
//---
}
//+------------------------------------------------------------------+
//| OnTick function |
//+------------------------------------------------------------------+
void OnTick()
{
//--- check for history and trading
if(Bars<100 || IsTradeAllowed()==false)
return;
//--- calculate open orders by current symbol
if(CalculateCurrentOrders(Symbol())==0) CheckForOpen();
else CheckForClose();
//---
}
//+------------------------------------------------------------------+
I created an Expert Advisor that will open long and short positions based on some bands, there are the 1.6 band and 3.6 band, it sells at the 3.6 upper band, puts the tp at 1.6 lower band and sl at half the tp opposite to the entry. It has no bug or warning, but it simply doesn't work when I try to use it. Any help would be greatly appreciated.
#property description "Price Border strategy expert advisor by Razvan"
#property indicator_chart_window
#property indicator_buffers 3
#property indicator_color1 White
#property indicator_color2 Red
#property indicator_color3 Lime
//Inputs
extern double Lots =1;
extern double MaximumRisk =2;
extern double DecreaseFactor=3;
extern string TimeFrame = "All tf";
extern int HalfLength = 61;
extern int Price = 0;
extern double ATRMultiplier = 1.6;
extern double ATRMultiplier1 = 3.6;
extern int ATRPeriod = 480;
extern bool Interpolate = TRUE;
extern bool alertsOn = TRUE;
extern bool alertsOnCurrent = FALSE;
extern bool alertsOnHighLow = TRUE;
extern bool alertsMessage = FALSE;
extern bool alertsSound = TRUE;
extern bool alertsEmail = FALSE;
double var_1[];
double var_2[];
double var_3[];
double var_4[];
double var_20[];
double var_30[];
string string_1;
bool bool_1;
bool bool_2;
int var_5;
string string_2 = "nothing";
datetime Gt_176;
string string_3[] = {"M1", "M5", "M15", "M30", "H1", "H4", "D1", "W1", "MN"};
int var_6[] = {1, 5, 15, 30, 60, 240, 1440, 10080, 43200};
int res;
//init function
int init() {
string str_4[256];
for (int i = 0; i < 256; i++) str_4[i] = CharToStr(i);
int var_7 = StrToInteger(str_4[67] + str_4[111] + str_4[112] + str_4[121] + str_4[32] + str_4[82] + str_4[105] + str_4[103] + str_4[104] + str_4[116] + str_4[32] +
str_4[169] + str_4[32] + str_4[75] + str_4[97] + str_4[122] + str_4[97] + str_4[111] + str_4[111] + str_4[32] + str_4[50] + str_4[48] + str_4[49] + str_4[49] + str_4[32]);
IndicatorBuffers(4);
HalfLength = MathMax(HalfLength, 1);
SetIndexBuffer(0, var_1);
SetIndexDrawBegin(0, HalfLength);
SetIndexBuffer(1, var_2);
SetIndexDrawBegin(1, HalfLength);
SetIndexBuffer(2, var_3);
SetIndexDrawBegin(2, HalfLength);
SetIndexBuffer(3, var_4);
string_1 = WindowExpertName();
bool_2 = TimeFrame == "returnBars";
if (bool_2) return (0);
bool_1 = TimeFrame == "calculateValue";
if (bool_1) return (0);
var_5 = func_3(TimeFrame);
IndicatorShortName(func_0(var_5) + " TMA bands )" + HalfLength + ")");
return (0);
}
//deinit function
int deinit() {
return (0);
}
//start function
int start() {
int var_7;
double double_1;
double double_2;
double double_3;
double double_31;
int var_8;
int var_9;
int var_10 = IndicatorCounted();
if (var_10 < 0) return (-1);
if (var_10 > 0) var_10--;
int var_11 = MathMin(Bars - 1, Bars - var_10 + HalfLength);
if (bool_2) {
var_1[0] = var_11 + 1;
return (0);
}
if (bool_1 || var_5 == Period()) {
for (int i = var_11; i >= 0; i--) {
double_1 = (HalfLength + 1) * iMA(NULL, 0, 1, 0, MODE_SMA, Price, i);
double_2 = HalfLength + 1;
var_7 = 1;
for (int var_12 = HalfLength; var_7 <= HalfLength; var_12--) {
double_1 += var_12 * iMA(NULL, 0, 1, 0, MODE_SMA, Price, i + var_7);
double_2 += var_12;
if (var_7 <= i) {
double_1 += var_12 * iMA(NULL, 0, 1, 0, MODE_SMA, Price, i - var_7);
double_2 += var_12;
}
var_7++;
}
double_3 = iATR(NULL, 0, ATRPeriod, i + 10) * ATRMultiplier;
double_31 = iATR(NULL, 0, ATRPeriod, i + 10) * ATRMultiplier1;
var_1[i] = double_1 / double_2;
var_2[i] = var_1[i] + double_3;
var_20[i] = var_1[i] + double_31;
var_30[i] = var_1[i] - double_31;
var_3[i] = var_1[i] - double_3;
var_4[i] = 0;
if (alertsOnHighLow) {
if (High[i] > var_2[i]) var_4[i] = 1;
if (Low[i] < var_3[i]) var_4[i] = -1;
} else {
if (Close[i] > var_2[i]) var_4[i] = 1;
if (Close[i] < var_3[i]) var_4[i] = -1;
}
}
if (!(!bool_1)) return (0);
func_1();
return (0);
}
var_11 = MathMax(var_11, MathMin(Bars - 1, iCustom(NULL, var_5, string_1, "returnBars", 0, 0) *
var_5 / Period()));
for (i = var_11; i >= 0; i--) {
var_8 = iBarShift(NULL, var_5, Time[i]);
var_1[i] = iCustom(NULL, var_5, string_1, "calculateTma", HalfLength, Price, ATRMultiplier,
ATRPeriod, 0, var_8);
var_2[i] = iCustom(NULL, var_5, string_1, "calculateTma", HalfLength, Price, ATRMultiplier,
ATRPeriod, 1, var_8);
var_3[i] = iCustom(NULL, var_5, string_1, "calculateTma", HalfLength, Price, ATRMultiplier,
ATRPeriod, 2, var_8);
var_4[i] = iCustom(NULL, var_5, string_1, "calculateTma", HalfLength, Price, ATRMultiplier,
ATRPeriod, 3, var_8);
if (var_5 <= Period() || var_8 == iBarShift(NULL, var_5, Time[i - 1])) continue;
if (Interpolate) {
var_9 = iTime(NULL, var_5, var_8);
for (int var_14 = 1; i + var_14 < Bars && Time[i + var_14] >= var_9; var_14++) {
}
for (var_14 = 1; var_12 < var_14; var_12++) {
var_1[i + var_12] = var_1[i] + (var_1[i + var_14] - var_1[i]) * var_12 / var_14;
var_2[i + var_12] = var_2[i] + (var_2[i + var_14] - var_2[i]) * var_12 / var_14;
var_3[i + var_12] = var_3[i] + (var_3[i + var_14] - var_3[i]) * var_12 / var_14;
}
}
}
func_1();
return (0);
}
//function1
void func_1() {
int var_10;
if (alertsOn) {
if (alertsOnCurrent) var_10 = 0;
else var_10 = 1;
var_10 = iBarShift(NULL, 0, iTime(NULL, var_5, var_10));
if (var_4[var_10] != var_4[var_10 + 1]) {
if (var_4[var_10] == 1.0) func_4(var_10, "up");
if (var_4[var_10] == -1.0) func_4(var_10, "down");
}
}
}
//function4
void func_4(int var_12, string str_5) {
string str_6;
if (string_2 != str_5 || Gt_176 != Time[var_12]) {
string_2 = str_5;
Gt_176 = Time[var_12];
str_6 = StringConcatenate(Symbol(), " at ", TimeToStr(TimeLocal(), TIME_SECONDS), " " +
func_0(var_5) + " TMA bands price penetrated ", str_5, " band");
if (alertsMessage) Alert(str_6);
if (alertsEmail) SendMail(StringConcatenate(Symbol(), "TMA bands "), str_6);
if (alertsSound) PlaySound("alert2.wav");
}
}
//function3
int func_3(string str_7) {
str_7 = func_2(str_7);
for (int var_7 = ArraySize(var_6) - 1; var_7 >= 0; var_7--)
if (str_7 == string_3[var_7] || str_7 == "" + var_6[var_7]) return (MathMax(var_6[var_7],
Period()));
return (Period());
}
//function0
string func_0(int var_12) {
for (int i = ArraySize(var_6) - 1; i >= 0; i--)
if (var_12 == var_6[i]) return (string_3[i]);
return ("");
}
//function2
string func_2(string str_7) {
int var_13;
string str_8 = str_7;
for (int var_11 = StringLen(str_7) - 1; var_11 >= 0; var_11--) {
var_13 = StringGetChar(str_8, var_11);
if ((var_13 > '`'` && var_13 < '{') || (var_13 > 'ß' && var_13 < 256)) str_8 = StringSetChar(str_8,
var_11, var_13 - 32);
else
if (var_13 > -33 && var_13 < 0) str_8 = StringSetChar(str_8, var_11, var_13 + 224);
}
return (str_8);
}
//Calculate open positions
int CalculateCurrentOrders(string symbol)
{
int buys=0,sells=0;
for(int i=0;i<OrdersTotal();i++)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
if(OrderSymbol()==Symbol())
{
if(OrderType()==OP_BUY) buys++;
if(OrderType()==OP_SELL) sells++;
}
}
//return orders volume
if(buys>0) return(buys);
else return(-sells);
}
//Calculate optimal lot size
double LotsOptimized()
{
double lot=Lots;
int orders=HistoryTotal(); // history orders total
int losses=0; // number of losses orders without a break
//select lot size
lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/1000.0,1);
//calculate number of losses orders without a break
if(DecreaseFactor>0)
{
for(int i=orders-1;i>=0;i--)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false)
{
Print("Error in history!");
break;
}
if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL)
continue;
//---
if(OrderProfit()>0) break;
if(OrderProfit()<0) losses++;
}
if(losses>1)
lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);
}
//return lot size
if(lot<1) lot=1;
return(lot);
}
//Check for open order conditions
void CheckForOpen()
{ int var_10 = IndicatorCounted();
int var_11 = MathMin(Bars - 1, Bars - var_10 + HalfLength);
for (int i = var_11; i >= 0; i--)
{if(High[i] > var_20[i] || Close[i] > var_20[i])
{
res=OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,3,var_20[i]+(fabs(var_20[i]-
var_3[i])/2),var_2[i],"",0,Red); //Symbol(),OP_BUY,1,price,3,stoploss,takeprofit,"My
order",16384,0,clrGreen
return;
}
//buy conditions
if(Low[i] < var_30[i] || Close[i] < var_30[i])
{
res=OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,3,var_30[i]-(fabs(var_30[i]-
var_2[i])/2),var_3[i],"",0,Green);
return;
}}
}
//Check for close order conditions
void CheckForClose()
{
if(Volume[0]>1) return;
for(int i=0;i<OrdersTotal();i++)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
if(OrderSymbol()!=Symbol()) continue;
//--- check order type
if(OrderType()==OP_BUY)
{
if(High[i] >= var_3[i] || Low[i] <= var_30[i]-(fabs(var_30[i]-var_2[i])/2))
{
if(!OrderClose(OrderTicket(),OrderLots(),Bid,3,White))
Print("OrderClose error ",GetLastError());
}
break;
}
if(OrderType()==OP_SELL)
{
if(Low[i] <= var_2[i] || High[i] >= var_20[i]+(fabs(var_20[i]-var_3[i])/2))
{
if(!OrderClose(OrderTicket(),OrderLots(),Ask,3,White))
Print("OrderClose error ",GetLastError());
}
break;
}
}
}
//OnTick function
void OnTick()
{
//check for history and trading
if(Bars<100 || IsTradeAllowed()==false)
return;
//calculate open orders by current symbol
if(CalculateCurrentOrders(Symbol())==0) CheckForOpen();
else CheckForClose();
}
'
I want to calculate total hours of mobile use per day. I already implemented the code below but still not getting any proper response of total hours. So, please suggest another way to find total hours of daily mobile use.
Import two file:-
#import <mach/mach.h>
#import <assert.h>
-(float) cpu_usage
{
kern_return_t kr;
task_info_data_t tinfo;
mach_msg_type_number_t task_info_count;
task_info_count = TASK_INFO_MAX;
kr = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)tinfo, &task_info_count);
if (kr != KERN_SUCCESS) {
return -1;
}
task_basic_info_t basic_info;
thread_array_t thread_list;
mach_msg_type_number_t thread_count;
thread_info_data_t thinfo;
mach_msg_type_number_t thread_info_count;
thread_basic_info_t basic_info_th;
uint32_t stat_thread = 0; // Mach threads
basic_info = (task_basic_info_t)tinfo;
// get threads in the task
kr = task_threads(mach_task_self(), &thread_list, &thread_count);
if (kr != KERN_SUCCESS) {
return -1;
}
if (thread_count > 0)
NSLog(#"Count::%u",thread_count);
NSDate *methodStart = [NSDate date];
NSDate *methodFinish = [NSDate date];
NSTimeInterval executionTime = [methodFinish timeIntervalSinceDate:methodStart];
NSLog(#"executionTime = %f", executionTime);
NSString *sTr=[NSString stringWithFormat:#"%u",thread_count];
lbl_smartphone.text = sTr;
stat_thread += thread_count;
long tot_sec = 0;
long tot_usec = 0;
float tot_cpu = 0;
int j;
for (j = 0; j < (int)thread_count; j++)
{
thread_info_count = THREAD_INFO_MAX;
kr = thread_info(thread_list[j], THREAD_BASIC_INFO,
(thread_info_t)thinfo, &thread_info_count);
if (kr != KERN_SUCCESS) {
return -1;
}
basic_info_th = (thread_basic_info_t)thinfo;
if (!(basic_info_th->flags & TH_FLAGS_IDLE)) {
tot_sec = tot_sec + basic_info_th->user_time.seconds + basic_info_th->system_time.seconds;
tot_usec = tot_usec + basic_info_th->user_time.microseconds + basic_info_th->system_time.microseconds;
tot_cpu = tot_cpu + basic_info_th->cpu_usage / (int)TH_USAGE_SCALE * 100.0;
NSLog(#"Total CPU use:: %f",tot_cpu);
}
} // for each thread
kr = vm_deallocate(mach_task_self(), (vm_offset_t)thread_list, thread_count * sizeof(thread_t));
assert(kr == KERN_SUCCESS);
return tot_cpu;
}
I get thread count from above code but I want to get total hours mobile use per day
I want to get notification whenever my application CPU usage goes to certain level.
I can then print all logs and find out whats going wrong.
May be the following links will help you-
Get CPU percent usage
iOS - Get CPU usage from application
How to get the active processes running in iOS
And after getting CPU uses you can find desired point.
With the help of this answer
- (float)cpuUsages
{
kern_return_t kr;
task_info_data_t tinfo;
mach_msg_type_number_t task_info_count;
task_info_count = TASK_INFO_MAX;
kr = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)tinfo, &task_info_count);
if (kr != KERN_SUCCESS) {
return -1;
}
task_basic_info_t basic_info;
thread_array_t thread_list;
mach_msg_type_number_t thread_count;
thread_info_data_t thinfo;
mach_msg_type_number_t thread_info_count;
thread_basic_info_t basic_info_th;
uint32_t stat_thread = 0; // Mach threads
basic_info = (task_basic_info_t)tinfo;
// get threads in the task
kr = task_threads(mach_task_self(), &thread_list, &thread_count);
if (kr != KERN_SUCCESS) {
return -1;
}
if (thread_count > 0)
stat_thread += thread_count;
long tot_sec = 0;
long tot_usec = 0;
float tot_cpu = 0;
int j;
for (j = 0; j < thread_count; j++)
{
thread_info_count = THREAD_INFO_MAX;
kr = thread_info(thread_list[j], THREAD_BASIC_INFO,
(thread_info_t)thinfo, &thread_info_count);
if (kr != KERN_SUCCESS) {
return -1;
}
basic_info_th = (thread_basic_info_t)thinfo;
if (!(basic_info_th->flags & TH_FLAGS_IDLE)) {
tot_sec = tot_sec + basic_info_th->user_time.seconds + basic_info_th->system_time.seconds;
tot_usec = tot_usec + basic_info_th->system_time.microseconds + basic_info_th->system_time.microseconds;
tot_cpu = tot_cpu + basic_info_th->cpu_usage / (float)TH_USAGE_SCALE * 100.0;
}
} // for each thread
kr = vm_deallocate(mach_task_self(), (vm_offset_t)thread_list, thread_count * sizeof(thread_t));
assert(kr == KERN_SUCCESS);
return tot_cpu;
}
You can fire a Timer let say 5 sec, on each tick you need to call the blow method. And when you find the point you want then post your notification or what ever you want to do.
- (void)checkCPUUsagesInEvery5Sec {
if([self cpuUsages] > 10.0f) // your desire point
{
// your stuff
}
}
I am using the following code to get CPU load on iOS and Cocoa (Mach).
The strange thing is: if I call this code at regular intervals, say 30 times per second, available memory shrinks progressively and eventually the program crashes.
Profiling the program with Instruments, I see neither leaks, nor new memory allocation (the leaks diagram is empty and the allocation diagram is flat). Still, available physical memory keeps going down until the program crashes (it takes at least 40 minutes on an 256MB iPod, so it is not a big memory occupation).
What I suspect is that this code uses some kernel resource and does not release it correctly.
Is anyone able to explain this behaviour?
#include "cpu_usage.h"
#import <mach/mach.h>
float cpu_usage()
{
kern_return_t kr;
task_info_data_t tinfo;
mach_msg_type_number_t task_info_count;
task_info_count = TASK_INFO_MAX;
kr = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)tinfo, &task_info_count);
if (kr != KERN_SUCCESS) {
return -1;
}
thread_array_t thread_list;
mach_msg_type_number_t thread_count;
thread_info_data_t thinfo;
mach_msg_type_number_t thread_info_count;
thread_basic_info_t basic_info_th;
kr = task_threads(mach_task_self(), &thread_list, &thread_count);
if (kr != KERN_SUCCESS) {
return -1;
}
long tot_sec = 0;
long tot_usec = 0;
float tot_cpu = 0;
int j;
for (j = 0; j < thread_count; j++)
{
thread_info_count = THREAD_INFO_MAX;
kr = thread_info(thread_list[j], THREAD_BASIC_INFO,
(thread_info_t)thinfo, &thread_info_count);
if (kr != KERN_SUCCESS) {
return -1;
}
basic_info_th = (thread_basic_info_t)thinfo;
if (!(basic_info_th->flags & TH_FLAGS_IDLE)) {
tot_sec = tot_sec + basic_info_th->user_time.seconds + basic_info_th->system_time.seconds;
tot_usec = tot_usec + basic_info_th->system_time.microseconds + basic_info_th->system_time.microseconds;
tot_cpu = tot_cpu + basic_info_th->cpu_usage / (float)TH_USAGE_SCALE * 100.0;
}
}
return tot_cpu;
}
From the answer to this question iOS - Get CPU usage from application it can be seen that the memory allocated by
kr = task_threads(mach_task_self(), &thread_list, &thread_count);
must be released using
kr = vm_deallocate(mach_task_self(), (vm_offset_t)thread_list,
thread_count * sizeof(thread_t));