#using <mscorlib.dll>
#using <System.dll>
using namespace System;
using namespace System::Text;
using namespace System::IO;
using namespace System::Net;
using namespace System::Net::Sockets;
using namespace System::Collections;
Errors: IntelliSense: "#using" requires C++/CLI to be enabled....
how to fix this prob!?
Your project settings are wrong. Specifically Configuration Properties, General, Common Language Runtime support.
Fall in the pit of success by starting your project by picking one of the project templates in the CLR node.
Choose Project -> Properties from the menu bar. In the Project properties window, under Configuration Properties -> General, make sure that Common Language Runtime Support is set to Common Language Runtime Support (/clr)
In VS2019 it the steps would be :
1/ Right click on the project
2/ Project
3/ Properties
4/ Configuration Properties
5/ Advanced
6/ Common Language Runtime Support change it to Common Language Runtime Support(/clr)
Enable it in your project settings (right click on the projet -> settings) the first tab should provide the option.
The MSDN has a nice example for testing the difference in performance, Parse vs tryParse:
Stopwatch Example
#include <stdio.h>
#using <System.dll>
using namespace System;
using namespace System::Diagnostics;
void DisplayTimerProperties()
{
// Display the timer frequency and resolution.
if (Stopwatch::IsHighResolution)
{
Console::WriteLine("Operations timed using the system's high-resolution performance counter.");
}
else
{
Console::WriteLine("Operations timed using the DateTime class.");
}
Int64 frequency = Stopwatch::Frequency;
Console::WriteLine(" Timer frequency in ticks per second = {0}", frequency);
Int64 nanosecPerTick = (1000L * 1000L * 1000L) / frequency;
Console::WriteLine(" Timer is accurate within {0} nanoseconds", nanosecPerTick);
}
void TimeOperations()
{
Int64 nanosecPerTick = (1000L * 1000L * 1000L) / Stopwatch::Frequency;
const long numIterations = 10000;
// Define the operation title names.
array<String^>^operationNames = { "Operation: Int32.Parse(\"0\")","Operation: Int32.TryParse(\"0\")","Operation: Int32.Parse(\"a\")","Operation: Int32.TryParse(\"a\")" };
// Time four different implementations for parsing
// an integer from a string.
for (int operation = 0; operation <= 3; operation++)
{
// Define variables for operation statistics.
Int64 numTicks = 0;
Int64 numRollovers = 0;
Int64 maxTicks = 0;
Int64 minTicks = Int64::MaxValue;
int indexFastest = -1;
int indexSlowest = -1;
Int64 milliSec = 0;
Stopwatch ^ time10kOperations = Stopwatch::StartNew();
// Run the current operation 10001 times.
// The first execution time will be tossed
// out, since it can skew the average time.
for (int i = 0; i <= numIterations; i++)
{
Int64 ticksThisTime = 0;
int inputNum;
Stopwatch ^ timePerParse;
switch (operation)
{
case 0:
// Parse a valid integer using
// a try-catch statement.
// Start a new stopwatch timer.
timePerParse = Stopwatch::StartNew();
try
{
inputNum = Int32::Parse("0");
}
catch (FormatException^)
{
inputNum = 0;
}
// Stop the timer, and save the
// elapsed ticks for the operation.
timePerParse->Stop();
ticksThisTime = timePerParse->ElapsedTicks;
break;
case 1:
// Parse a valid integer using
// the TryParse statement.
// Start a new stopwatch timer.
timePerParse = Stopwatch::StartNew();
if (!Int32::TryParse("0", inputNum))
{
inputNum = 0;
}
// Stop the timer, and save the
// elapsed ticks for the operation.
timePerParse->Stop();
ticksThisTime = timePerParse->ElapsedTicks;
break;
case 2:
// Parse an invalid value using
// a try-catch statement.
// Start a new stopwatch timer.
timePerParse = Stopwatch::StartNew();
try
{
inputNum = Int32::Parse("a");
}
catch (FormatException^)
{
inputNum = 0;
}
// Stop the timer, and save the
// elapsed ticks for the operation.
timePerParse->Stop();
ticksThisTime = timePerParse->ElapsedTicks;
break;
case 3:
// Parse an invalid value using
// the TryParse statement.
// Start a new stopwatch timer.
timePerParse = Stopwatch::StartNew();
if (!Int32::TryParse("a", inputNum))
{
inputNum = 0;
}
// Stop the timer, and save the
// elapsed ticks for the operation.
timePerParse->Stop();
ticksThisTime = timePerParse->ElapsedTicks;
break;
default:
break;
}
// Skip over the time for the first operation,
// just in case it caused a one-time
// performance hit.
if (i == 0)
{
time10kOperations->Reset();
time10kOperations->Start();
}
else
{
// Update operation statistics
// for iterations 1-10001.
if (maxTicks < ticksThisTime)
{
indexSlowest = i;
maxTicks = ticksThisTime;
}
if (minTicks > ticksThisTime)
{
indexFastest = i;
minTicks = ticksThisTime;
}
numTicks += ticksThisTime;
if (numTicks < ticksThisTime)
{
// Keep track of rollovers.
numRollovers++;
}
}
}
// Display the statistics for 10000 iterations.
time10kOperations->Stop();
milliSec = time10kOperations->ElapsedMilliseconds;
Console::WriteLine();
Console::WriteLine("{0} Summary:", operationNames[operation]);
Console::WriteLine(" Slowest time: #{0}/{1} = {2} ticks", indexSlowest, numIterations, maxTicks);
Console::WriteLine(" Fastest time: #{0}/{1} = {2} ticks", indexFastest, numIterations, minTicks);
Console::WriteLine(" Average time: {0} ticks = {1} nanoseconds", numTicks / numIterations, (numTicks * nanosecPerTick) / numIterations);
Console::WriteLine(" Total time looping through {0} operations: {1} milliseconds", numIterations, milliSec);
}
}
int main()
{
DisplayTimerProperties();
Console::WriteLine();
Console::WriteLine("Press the Enter key to begin:");
Console::ReadLine();
Console::WriteLine();
TimeOperations();
getchar();
}
//Operations timed using the system's high-resolution performance counter.
//Timer frequency in ticks per second = 3319338
//Timer is accurate within 301 nanoseconds
//
//Press the Enter key to begin :
//
//
//
//Operation : Int32.Parse("0") Summary :
// Slowest time : #4483 / 10000 = 95 ticks
// Fastest time : #3 / 10000 = 0 ticks
// Average time : 0 ticks = 99 nanoseconds
// Total time looping through 10000 operations : 1 milliseconds
//
// Operation : Int32.TryParse("0") Summary :
// Slowest time : #7720 / 10000 = 187 ticks
// Fastest time : #1 / 10000 = 0 ticks
// Average time : 0 ticks = 109 nanoseconds
// Total time looping through 10000 operations : 1 milliseconds
//
// Operation : Int32.Parse("a") Summary :
// Slowest time : #3701 / 10000 = 2388 ticks
// Fastest time : #2698 / 10000 = 102 ticks
// Average time : 116 ticks = 35109 nanoseconds
// Total time looping through 10000 operations : 352 milliseconds
//
// Operation : Int32.TryParse("a") Summary :
// Slowest time : #8593 / 10000 = 23 ticks
// Fastest time : #1 / 10000 = 0 ticks
// Average time : 0 ticks = 88 nanoseconds
// Total time looping through 10000 operations : 1 milliseconds
If you are using Visual Studio, you might have to do some installations pre-hand. To install those, open the Visual Studio Installer from the Windows Start menu. Make sure that the Desktop development with C++ tile is checked, and in the Optional components section, also check C++/CLI Support.
Related
I have my own test class that is supposed to do timing without JVM deleting anything. Some example test times of 100,000,000 reps comparing the native that Java calls from StrictMath.sin() to my own:
30 degrees
sineNative(): 18,342,858 ns (#1), 1,574,331 ns (#10)
sinCosTanNew6(): 13,751,140 ns (#1), 1,569,848 ns (#10)
60 degrees
sineNative(): 2,520,327,020 ns (#1), 2,520,108,337 ns (#10)
sinCosTanNew6(): 12,935,959 ns (#1), 1,565,365 ns (#10)
From 30 to 60 native time skyrockets * 137 while mine is ~constant. Also, some of the times are impossibly low even when repsDone returns == reps. I expect they should be > 1*reps.
CPU: G3258 # 4GHz
OS: Windows 7 HB SP1
Build Path: jre1.8.0_211
Reprex:
public final class MathTest {
private static int sysReps = 1_000_000;
private static double value = 0;
private static final double DRAD_ANGLE_30 = 0.52359877559829887307710723054658d;
private static final double DRAD_ANGLE_60 = 1.0471975511965977461542144610932d;
private static double sineNative(double angle ) {
int reps = sysReps * 100;
//int repsDone = 0;
value = 0;
long startTime, endTime, timeDif;
startTime = System.nanoTime();
for (int index = reps - 1; index >= 0; index--) {
value = Math.sin(angle);
//repsDone++;
}
endTime = System.nanoTime();
timeDif = endTime - startTime;
System.out.println("sineNative(): " + timeDif + "ns for " + reps + " sine " + value + " of angle " + angle);
//System.out.println("reps done: "+repsDone);
return value;
}
private static void testSines() {
sineNative(DRAD_ANGLE_30);
//sinCosTanNew6(IBIT_ANGLE_30);
}
/* Warm Up */
private static void repeatAll(int reps) {
for (int index = reps - 1; index >= 0; index--) {
testSines();
}
}
public static void main(String[] args) {
repeatAll(10);
}
}
I tried adding angle++ in the loop and that multiplies the times to a more reasonable level, but that messes with the math. I need a way to trick it into the running all of the code all x times. Single pass times are extremely volatile and calling nanotime() takes time, so I need the average of a large number.
The problem is that you never use/refer to the results returned by sineNative. The JIT compiler is clever enough to work out that you never use the return value, so it will just do nothing eventually. A very simple way to fix this is to add a dummy check for your return value. (e.g. if (Math.sin(angle) > 1) { System.out.println("Impossible!"); })
If you are writing benchmark like this it would be useful to use something like JMH (https://github.com/openjdk/jmh) which would automatically create a blackhole for your return variable, so that the JIT compiler will not optimise the value. (see example https://github.com/openjdk/jmh/blob/master/jmh-samples/src/main/java/org/openjdk/jmh/samples/JMHSample_09_Blackholes.java)
How could I generate steady CPU load in C#, lower than 100% for a certain time? I would also like to be able to change the load amount after a certain period of time. How do you recommend to generate usage spikes for a very short time?
First off, you have to understand that CPU usage is always an average over a certain time. At any given time, the CPU is either working or it is not. The CPU is never 40% working.
We can, however, simulate a 40% load over say a second by having the CPU work for 0.4 seconds and sleep 0.6 seconds. That gives an average utilization of 40% over that second.
Cutting it down to smaller than one second, say 100 millisecond chunks should give even more stable utilization.
The following method will take an argument that is desired utilization and then utilize a single CPU/core to that degree:
public static void ConsumeCPU(int percentage)
{
if (percentage < 0 || percentage > 100)
throw new ArgumentException("percentage");
Stopwatch watch = new Stopwatch();
watch.Start();
while (true)
{
// Make the loop go on for "percentage" milliseconds then sleep the
// remaining percentage milliseconds. So 40% utilization means work 40ms and sleep 60ms
if (watch.ElapsedMilliseconds > percentage)
{
Thread.Sleep(100 - percentage);
watch.Reset();
watch.Start();
}
}
}
I'm using a stopwatch here because it is more accurate than the the TickCount property, but you could likewise use that and use subtraction to check if you've run long enough.
Two things to keep in mind:
on multi core systems, you will have to spawn one thread for each core. Otherwise, you'll see only one CPU/core being exercised giving roughly "percentage/number-of-cores" utilization.
Thread.Sleep is not very accurate. It will never guarantee times exactly to the millisecond so you will see some variations in your results
To answer your second question, about changing the utilization after a certain time, I suggest you run this method on one or more threads (depending on number of cores) and then when you want to change utilization you just stop those threads and spawn new ones with the new percentage values. That way, you don't have to implement thread communication to change percentage of a running thread.
Just in add of the Isak response, I let here a simple implementation for multicore:
public static void CPUKill(object cpuUsage)
{
Parallel.For(0, 1, new Action<int>((int i) =>
{
Stopwatch watch = new Stopwatch();
watch.Start();
while (true)
{
if (watch.ElapsedMilliseconds > (int)cpuUsage)
{
Thread.Sleep(100 - (int)cpuUsage);
watch.Reset();
watch.Start();
}
}
}));
}
static void Main(string[] args)
{
int cpuUsage = 50;
int time = 10000;
List<Thread> threads = new List<Thread>();
for (int i = 0; i < Environment.ProcessorCount; i++)
{
Thread t = new Thread(new ParameterizedThreadStart(CPUKill));
t.Start(cpuUsage);
threads.Add(t);
}
Thread.Sleep(time);
foreach (var t in threads)
{
t.Abort();
}
}
For a uniform stressing: Isak Savo's answer with a slight tweak. The problem is interesting. In reality there are workloads that far exceed it in terms of wattage used, thermal output, lane saturation, etc. and perhaps the use of a loop as the workload is poor and almost unrealistic.
int percentage = 80;
for (int i = 0; i < Environment.ProcessorCount; i++)
{
(new Thread(() =>
{
Stopwatch watch = new Stopwatch();
watch.Start();
while (true)
{
// Make the loop go on for "percentage" milliseconds then sleep the
// remaining percentage milliseconds. So 40% utilization means work 40ms and sleep 60ms
if (watch.ElapsedMilliseconds > percentage)
{
Thread.Sleep(100 - percentage);
watch.Reset();
watch.Start();
}
}
})).Start();
}
Each time you have to set cpuUsageIncreaseby variable.
for example:
1- Cpu % increase by > cpuUsageIncreaseby % for one minute.
2- Go down to 0% for 20 seconds.
3- Goto step 1.
private void test()
{
int cpuUsageIncreaseby = 10;
while (true)
{
for (int i = 0; i < 4; i++)
{
//Console.WriteLine("am running ");
//DateTime start = DateTime.Now;
int cpuUsage = cpuUsageIncreaseby;
int time = 60000; // duration for cpu must increase for process...
List<Thread> threads = new List<Thread>();
for (int j = 0; j < Environment.ProcessorCount; j++)
{
Thread t = new Thread(new ParameterizedThreadStart(CPUKill));
t.Start(cpuUsage);
threads.Add(t);
}
Thread.Sleep(time);
foreach (var t in threads)
{
t.Abort();
}
//DateTime end = DateTime.Now;
//TimeSpan span = end.Subtract(start);
//Console.WriteLine("Time Difference (seconds): " + span.Seconds);
//Console.WriteLine("10 sec wait... for another.");
cpuUsageIncreaseby = cpuUsageIncreaseby + 10;
System.Threading.Thread.Sleep(20000);
}
}
}
I'm trying to make a loop execute regularly every 50 milliseconds on an Atmega 2560. Using a simple delay function won't work, because the total loop time ends up being the time it took to execute the other functions in the loop, plus your delay time. This works even less well if your functions calls take variable time, which they usually will.
To solve this, I implemented a simple timer class:
volatile unsigned long timer0_ms_tick;
timer::timer()
{
// Set timer0 registers
TCCR0A = 0b00000000; // Nothing here
TCCR0B = 0b00000000; // Timer stopped, begin function start by setting last three bits to 011 for prescaler of 64
TIMSK0 = 0b00000001; // Last bit to 1 to enable timer0 OFV interrupt enable
sei(); // Enable global interrupts
}
void timer::start()
{
timer0_ms_tick = 0;
// Set timer value for 1ms tick (2500000 ticks/sec)*(1 OFV/250 ticks) = 1000OVF/sec
// 256ticks - 250ticks - 6 ticks, but starting at 0 means setting to 5
TCNT0 = 5;
// Set prescaler and start timer
TCCR0B = 0b00000011;
}
unsigned long timer::now_ms()
{
return timer0_ms_tick;
}
ISR(TIMER0_OVF_vect)
{
timer0_ms_tick+=1;
TCNT0 = 5;
}
The main loop uses this like so:
unsigned long startTime, now;
while(true)
{
startTime = startup_timer.now_ms();
/* Loop Functions */
// Wait time step
now = startup_timer.now_ms();
while(now-startTime < 50)
{
now = startup_timer.now_ms();
}
Serial0.print(ltoa(now,time_string, 10));
Serial0.writeChar('-');
Serial0.print(ltoa(startTime,time_string, 10));
Serial0.writeChar('=');
Serial0.println(ltoa(now-startTime,time_string, 10));
}
My output looks like this:
11600-11550=50
11652-11602=50
11704-11654=50
11756-11706=50
12031-11758=273
11828-11778=50
11880-11830=50
11932-11882=50
11984-11934=50
12036-11986=50
12088-12038=50
12140-12090=50
12192-12142=50
12244-12194=50
12296-12246=50
12348-12298=50
12400-12350=50
12452-12402=50
12504-12454=50
12556-12506=50
12608-12558=50
12660-12610=50
12712-12662=50
12764-12714=50
12816-12766=50
12868-12818=50
12920-12870=50
12972-12922=50
13024-12974=50
13076-13026=50
13128-13078=50
13180-13130=50
13232-13182=50
13284-13234=50
13336-13286=50
13388-13338=50
13440-13390=50
13492-13442=50
13544-13494=50
13823-13546=277
13620-13570=50
It seems to work well most of the time, but every once in a while something odd will happen with the timing values. I think it has something to do with the interrupt, but I'm not sure what. Any help would be greatly appreciated.
I'm trying to use the systemLock() to lock the device when the getSpeed() returns a value greater than 20 m/s.
public void locationUpdated(LocationProvider provider, Location location)
{
if(location.isValid())
{
float speed = location.getSpeed();
// Information to be displayed on the device
StringBuffer sb = new StringBuffer();
sb.append("\n");
sb.append("Speed : ");
sb.append(speed);
sb.append(" m/s");
if(speed < 20){
appMan = ApplicationManager.getApplicationManager();
appMan.lockSystem(true);
}else{
}
MyApp.this.updateLocationScreen(sb.toString());
}
}
I have a RichTextField and I can use the .settext() successfully in the if/else statement to change the RichTextField's text so I must be using the lockSystem() wrong.
Edit
if(speed > 20 || Double.isNaN(speed)){
requestForeground();
appMan = ApplicationManager.getApplicationManager();
appMan.lockSystem(true);
}else{
}
The first thing that comes to the eyes is:
to lock the device when the getSpeed() returns a value greater than 20 m/s.
and
if (speed < 20) {
appMan = ApplicationManager.getApplicationManager();
appMan.lockSystem(true);
}
From the docs on Location
public float getSpeed()
Returns:
the current ground speed in m/s for
the terminal or Float.NaN if the speed is not known
In Java, any comparison against Float.NaN will return false, so your lock screen code block won't execute if your device is returning NaN as the speed. You might want to add Double.isNaN(speed) to your condition.
The overview tab of a process on jconsole shows me the CPU Usage percentage. Is there a MBean that gives me this value? What is its ObjectName?
Update: In Java 7 you can do it like so:
public static double getProcessCpuLoad() throws MalformedObjectNameException, ReflectionException, InstanceNotFoundException {
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName name = ObjectName.getInstance("java.lang:type=OperatingSystem");
AttributeList list = mbs.getAttributes(name, new String[]{ "ProcessCpuLoad" });
if (list.isEmpty()) return Double.NaN;
Attribute att = (Attribute)list.get(0);
Double value = (Double)att.getValue();
if (value == -1.0) return Double.NaN;
return ((int)(value * 1000) / 10.0); // returns a percentage value with 1 decimal point precision
}
----- original answer below -----
In Java 7 you can use the hidden methods of com.sun.management.OperatingSystemMXBean:
getProcessCpuLoad() // returns the CPU usage of the JVM
getSystemCpuLoad() // returns the CPU usage of the whole system
Both values are returned as a double between 0.0 and 1.0 so simply multiply by 100 to get a percentage.
com.sun.management.OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
System.out.println(osBean.getProcessCpuLoad() * 100);
System.out.println(osBean.getSystemCpuLoad() * 100);
Since these are hidden, undocumented, methods that exist in com.sun.management.OperatingSystemMXBean package and not in the java.lang.management.OperatingSystemMXBean there is a risk that they will not be available in some JVMs or in future updates, so you should decide if you're willing to take that risk or not.
see https://www.java.net/community-item/hidden-java-7-features-%E2%80%93-system-and-process-cpu-load-monitoring for more.
There does not seem to be a direct MBean within ManagementFactory. The closest is http://java.sun.com/javase/6/docs/api/java/lang/management/OperatingSystemMXBean.html#getSystemLoadAverage() which can be used to calculate the CPU used by the whole system.
However this URL has suggested a method based on the source code of jconsole
I modified a code from internet, like this, then I tested that and the result almost match the linux ps command's result.
/** below is the code */
public float getCpuUsed() {
/** get a MXBean */
com.sun.management.OperatingSystemMXBean osMXBean =
(com.sun.management.OperatingSystemMXBean)
ManagementFactory.getOperatingSystemMXBean();
/** set old timestamp values */
long previousJvmProcessCpuTime = osMXBean.getProcessCpuTime();
int sleepTime = 350;
/** sleep for a while to use to calculate */
try {
TimeUnit.MILLISECONDS.sleep(sleepTime);
} catch (InterruptedException e) {
logger.error("InterruptedException occurred while MemoryCollector sleeping...");
}
/** elapsed process time is in nanoseconds */
long elapsedProcessCpuTime = osMXBean.getProcessCpuTime() - previousJvmProcessCpuTime;
/** elapsed uptime is in milliseconds */
long elapsedJvmUptime = sleepTime ;
/** total jvm uptime on all the available processors */
//long totalElapsedJvmUptime = elapsedJvmUptime * osMXBean.getAvailableProcessors() ;
long totalElapsedJvmUptime = elapsedJvmUptime;
//System.out.println("echo cpu processors num " + osMXBean.getAvailableProcessors());
/** calculate cpu usage as a percentage value
to convert nanoseconds to milliseconds divide it by 1000000 and to get a percentage multiply it by 100 */
float cpuUsage = elapsedProcessCpuTime / (totalElapsedJvmUptime * 10000F);
return (float)(Math.round(cpuUsage*10)/10);
}
Iff you are using UNIX based OS then it's way much easier
final OperatingSystemMXBean mxBean = ManagementFactory.getOperatingSystemMXBean();
if (mxBean instanceof UnixOperatingSystemMXBean) {
return ((UnixOperatingSystemMXBean) mxBean).getSystemCpuLoad() * 100.0;
}