YUI Compressor: What are micro optimizations? - yui-compressor

YUI Compressor, in its (not very extensive) documentation states this as an option:
--disable-optimizations
Disable all the built-in micro optimizations.
Does anyone know what this means?
What will this turn on/off?
I haven't found any documentation about it.
Thanks!

Looking at the source of JavaScriptCompressor:
lines 548-
if (!disableOptimizations) {
optimizeObjectMemberAccess(this.tokens);
optimizeObjLitMemberDecl(this.tokens);
}
lines 467 -
/*
* Transforms obj["foo"] into obj.foo whenever possible, saving 3 bytes.
*/
private static void optimizeObjectMemberAccess(ArrayList tokens) {
lines 497 -
/*
* Transforms 'foo': ... into foo: ... whenever possible, saving 2 bytes.
*/
private static void optimizeObjLitMemberDecl(ArrayList tokens) {
So it's converting use of constant strings in foo['bar'] to foo.bar and {'bar':x} to {bar:x}.

Related

How to properly log Vulkan result type strings

Logging VkResult enum values
The VkResult enum contains a lot of values. Unfortunately though, they are C enums which aliases an integer, so I cannot easily just log their names to the console. For this purpose, I am envisioning a function which does something like this:
void graphics::log_vk_result(VkResult result)
{
switch (result)
{
case VK_SUCCESS:
log_core_debug("VK_SUCCESS"); return;
case VK_NOT_READY:
log_core_debug("VK_NOT_READY"); return;
[...]
}
But some of the enum values are only supported by certain extensions, as indicated here. An example: The extension VK_EXT_debug_report introduces the following value to the enumeration: VK_ERROR_VALIDATION_FAILED_EXT. So my idea for (potentially) more portable code would be something like this:
void graphics::log_vk_result(VkResult result)
{
switch (result)
{
[...]
#if defined(VK_EXT_DEBUG_REPORT_EXTENSION_NAME)
case VK_ERROR_VALIDATION_FAILED_EXT:
log_core_debug("VK_ERROR_VALIDATION_FAILED_EXT");
#endif
}
I found this name by looking at the extension manual page. I cannot easily see whether or not VK_EXT_DEBUG_REPORT_EXTENSION_NAME is a macro or an enum - it is a const char* but stated under the section "New Enum Constants". So checking for this particular value, for this particular extension, was my default choice.
[I do realize this extension is marked as deprecated, and I'm not using it! I only use it as an example here.]
I have two questions:
Is this needed?
Is this the correct way of doing this?
Thanks a lot!
All of this is unnecessary, since Vulkan SDK already includes the desired functionality:
#include <vulkan/vk_enum_string_helper.h>
void graphics::log_vk_result( const VkResult result ){
log_core_debug( string_VkResult(result) );
}

Ensuring JMH benchmark method gets compiled

I have a benchmark with a #Param controlling the input size, such as:
#State(Scope.Benchmark)
class MyBenchmark {
#Param({"100", "10000", "1000000"})
public int ARRAY_SIZE;
public int[] INPUT;
#Setup
public void setUp() {
INPUT = new int[ARRAY_SIZE];
// ...
}
#Benchmark
public void compute() {
// ...
}
}
When the input is large, compute doesn't get invoked enough times to trigger compilation during warmup. Since I would like to measure peak performance, I want to ensure the method is invoked enough during warmup to be compiled.
Is there a good way to do this? I could set a higher number of warmup iterations, but this would apply to all input sizes when it's really only necessary for the large ones which don't get compiled.
Instead of increasing the number of iterations, you can try making compilation happen earlier.
Since JDK 9, there is -XX:CompileThresholdScaling JVM option to adjust frequencies and thresholds of the compilation policy. The lower is the value - the earlier compilation starts.
E.g. -XX:CompileThresholdScaling=0.05 will make thresholds 20x lower.
The option can be applied globally or on a per-method basis. For example, to apply it only to compute benchmark, add the following annotation:
#Benchmark
#Fork(jvmArgsAppend = {"-XX:CompileCommand=CompileThresholdScaling,*MyBenchmark*::compute*,0.05"})
public void compute() {
// ...
}
Alternatively, you may extract larger parameter values into another #State object and create a separate benchmark method with different #Warmup options:
#State(Scope.Benchmark)
public static class SmallParams {
#Param({"100", "10000"})
int size;
}
#State(Scope.Benchmark)
public static class LargeParams {
#Param({"1000000"})
int size;
}
#Benchmark
#Warmup(iterations = 5)
public void computeSmall(SmallParams params) {
//
}
#Benchmark
#Warmup(iterations = 50)
public void computeLarge(LargeParams params) {
//
}
Or just run the benchmark twice, overriding parameters in the command line:
-p size=100,10000 -wi 5
-p size=1000000 -wi 50

Accessing a C/C++ structure of callbacks through a DLL's exported function using JNA

I have a vendor supplied .DLL and an online API that I am using to interact with a piece of radio hardware; I am using JNA to access the exported functions through Java (because I don't know C/C++). I can call basic methods and use some API structures successfully, but I am having trouble with the callback structure. I've followed the TutorTutor guide here and also tried Mr. Wall's authoritative guide here, but I haven't been able to formulate the Java side syntax for callbacks set in a structure correctly.
I need to use this exported function:
BOOL __stdcall SetCallbacks(INT32 hDevice,
CONST G39DDC_CALLBACKS *Callbacks, DWORD_PTR UserData);
This function references the C/C++ Structure:
typedef struct{
G39DDC_IF_CALLBACK IFCallback;
//more omitted
} G39DDC_CALLBACKS;
...which according to the API has these Members (Note this is not an exported function):
VOID __stdcall IFCallback(CONST SHORT *Buffer, UINT32 NumberOfSamples,
UINT32 CenterFrequency, WORD Amplitude,
UINT32 ADCSampleRate, DWORD_PTR UserData);
//more omitted
I have a G39DDCAPI.java where I have loaded the DLL library and reproduced the API exported functions in Java, with the help of JNA. Simple calls to that work well.
I also have a G39DDC_CALLBACKS.java where I have implemented the above C/C++ structure in a format works for other API structures. This callback structure is where I am unsure of the syntax:
import java.util.Arrays;
import java.util.List;
import java.nio.ShortBuffer;
import com.sun.jna.Structure;
import com.sun.jna.platform.win32.BaseTSD.DWORD_PTR;
import com.sun.jna.win32.StdCallLibrary.StdCallCallback;
public class G39DDC_CALLBACKS extends Structure {
public G39DDC_IF_CALLBACK IFCallback;
//more omitted
protected List getFieldOrder() {
return Arrays.asList(new String[] {
"IFCallback","DDC1StreamCallback" //more omitted
});
}
public static interface G39DDC_IF_CALLBACK extends StdCallCallback{
public void invoke(ShortBuffer _Buffer,int NumberOfSamples,
int CenterFrequency, short Amplitude,
int ADCSampleRate, DWORD_PTR UserData);
}
}
Edit: I made my arguments more type safe as Technomage suggested. I am still getting a null pointer exception with several attempts to call the callback. Since I'm not sure of my syntax regarding the callback structure above, I can't pinpoint my problem in the main below. Right now the relevant section looks like this:
int NumberOfSamples=65536;//This is usually 65536.
ShortBuffer _Buffer = ShortBuffer.allocate(NumberOfSamples);
int CenterFrequency=10000000;//Specifies center frequency (in Hz) of the useful band
//in received 50 MHz wide snapshot.
short Amplitude=0;//The possible value is 0 to 32767.
int ADCSampleRate=100;//Specifies sample rate of the ADC in Hz.
DWORD_PTR UserData = null;
G39DDC_CALLBACKS callbackStruct= new G39DDC_CALLBACKS();
lib.SetCallbacks(hDevice,callbackStruct,UserData);
//hDevice is a handle for the hardware device used-- works in other uses
//lib is a reference to the library in G39DDCAPI.java-- works in other uses
//The UserData is a big unknown-- I don't know what to do with this variable
//as a DWORD_PTR
callbackStruct.IFCallback.invoke(_Buffer, NumberOfSamples, CenterFrequency,
Amplitude, ADCSampleRate, UserData);
EDIT NO 2:
I have one callback working somewhat, but I don't have control over the buffers. More frustratingly, a single call to invoke the method will result in several runs of the custom callback, usually with multiple output files (results vary drastically from run to run). I don't know if it is because I am not allocating memory correctly on the Java side, because I cannot free the memory on the C/C++ side, or because I have no cue on which to tell Java to access the buffer, etc. Relevant code looks like:
//before this, main method sets library, starts DDCs, initializes some variables...
//API call to start IF
System.out.print("Starting IF... "+lib.StartIF(hDevice, Period)+"\n")
G39DDC_CALLBACKS callbackStructure = new G39DDC_CALLBACKS();
callbackStructure.IFCallback = new G39DDC_IF_CALLBACK(){
#Override
public void invoke(Pointer _Buffer, int NumberOfSamples, int CenterFrequency,
short Amplitude, int ADCSampleRate, DWORD_PTR UserData ) {
//notification
System.out.println("Invoked IFCallback!!");
try {
//ready file and writers
File filePath = new File("/users/user/G39DDC_Scans/");
if (!filePath.exists()){
System.out.println("Making new directory...");
filePath.mkdir();
}
String filename="Scan_"+System.currentTimeMillis();
File fille= new File("/users/user/G39DDC_Scans/"+filename+".txt");
if (!fille.exists()) {
System.out.println("Making new file...");
fille.createNewFile();
}
FileWriter fw = new FileWriter(fille.getAbsoluteFile());
//callback body
short[] deBuff=new short[NumberOfSamples];
int offset=0;
int arraySize=NumberOfSamples;
deBuff=_Buffer.getShortArray(offset,arraySize);
for (int i=0; i<NumberOfSamples; i++){
String str=deBuff[i]+",";
fw.write(str);
}
fw.close();
} catch (IOException e1) {
System.out.println("IOException: "+e1);
}
}
};
lib.SetCallbacks(hDevice, callbackStructure,UserData);
System.out.println("Main, before callback invocation");
callbackStructure.IFCallback.invoke(s_Pointer, NumberOfSamples, CenterFrequency, Amplitude, ADCSampleRate, UserData);
System.out.println("Main, after callback invocation");
//suddenly having trouble stopping DDCs or powering off device; assume it has to do with dll using the functions above
//System.out.println("StopIF: " + lib.StopIF(hDevice));//API function returns boolean value
//System.out.println("StopDDC2: " + lib.StopDDC2( hDevice, Channel));
//System.out.println("StopDDC1: " + lib.StopDDC1( hDevice, Channel ));
//System.out.println("test_finishDevice: " + test_finishDevice( hDevice, lib));
System.out.println("Program Exit");
//END MAIN METHOD
You need to extend StdCallCallback, for one, otherwise you'll likely crash when the native code tries to call the Java code.
Any place you see a Windows type with _PTR, you should use a PointerType - the platform package with JNA includes definitions for DWORD_PTR and friends.
Finally, you can't have a primitive array argument in your G39DDC_IF_CALLBACK. You'll need to use Pointer or an NIO buffer; Pointer.getShortArray() may then be used to extract the short[] by providing the desired length of the array.
EDIT
Yes, you need to initialize your callback field in the callbacks structure before passing it into your native function, otherwise you're just passing a NULL pointer, which will cause complaints on the Java or native side or both.
This is what it takes to create a callback, using an anonymous instance of the declared callback function interface:
myStruct.callbackField = new MyCallback() {
public void invoke(int arg) {
// do your stuff here
}
};

How to use interlocked operations against memory-mapped files in .Net

Is there any way to use the Interlocked.CompareExchange(); and Interlocked.Increment(); methods against values stored in a memory-mapped file?
I'd like to implement a multi-threaded service that will store its data in a memory-mapped file, but since it's multi-threaded I need to prevent conflicting writes, therefore I wonder about the Interlocked operations rather than using explicit locks.
I know it's possible with native code, but can it be done in managed code on .NET 4.0?
OK, this is how you do it! We had to figure this out, and I figured we could give some back to stackoverflow!
class Program
{
internal static class Win32Stuff
{
[DllImport("kernel32.dll", SetLastError = true)]
unsafe public static extern int InterlockedIncrement(int* lpAddend);
}
private static MemoryMappedFile _mmf;
private static MemoryMappedViewStream _mmvs;
unsafe static void Main(string[] args)
{
const int INT_OFFSET = 8;
_mmf = MemoryMappedFile.CreateOrOpen("SomeName", 1024);
// start at offset 8 (just for example)
_mmvs = _mmf.CreateViewStream(INT_OFFSET, 4);
// Gets the pointer to the MMF - we dont have to worry about it moving because its in shared memory
var ptr = _mmvs.SafeMemoryMappedViewHandle.DangerousGetHandle();
// Its important to add the increment, because even though the view says it starts at an offset of 8, we found its actually the entire memory mapped file
var result = Win32Stuff.InterlockedIncrement((int*)(ptr + INT_OFFSET));
}
}
This does work, and works across multiple processes! Always enjoy a good challenge!
TravisWhidden, actually you can use Interlocked.Increment Static method as dan-gph said, you just have to be careful with pointer casting and operator priority, plus parenthesis usage, in facts...
You'll cast a memory pointer (plus the desired offset), into a pointer to an int variable, then you'll use that pointer as a variable. Then you'll have to use it as a variable reference.
Below you'll find the corresponding snippet of yours using .net library instead of external static import.
P&L
class Program
{
private static MemoryMappedFile _mmf;
private static MemoryMappedViewStream _mmvs;
static void Main(string[] args)
{
const int INT_OFFSET = 8;
_mmf = MemoryMappedFile.CreateOrOpen("SomeName", 1024);
_mmvs = _mmf.CreateViewStream(INT_OFFSET, 4);
unsafe
{
IntPtr ptr = _mmvs.SafeMemoryMappedViewHandle.DangerousGetHandle();
Interlocked.Increment(ref (*((int*)(ptr + INT_OFFSET)))
}
}
}

Casting a basic CFTypeRef to a more specific CoreFoundation type

Is there a simple way to convert a CTypeRef to a specific CoreFoundation type? I'm not looking to cast inline as (CFStringRef)myObjectRef but would like to create a helper method to do this for me for all CoreFoundation types.
I know it's possible to use something like CFGetTypeID(myObjectRef) == CFStringGetTypeID() to find out whether a CTypeRef is a CFString. However creating a single method to do this could become very verbose and have a lot of if statements.
Is building out a method with a bunch of if statements against CFGetTypeID() the only way? Or is there a simpler way to do this?
UPDATE: with example
I'd like to make a helper function to work with some legacy code I can't change. Currently it produces one of CFDictionaryRef, CFStringRef or CFURLRef as a return value provided as a CTypeRef. I'm currently working around this by running CFGetTypeID() on the returned value but this isn't ideal. Rather than having C-style casts all over the place, I'd rather have a CastToCF() helper which handles this for me. This would help make testing easier in the future as well.
P.S. I'm not worried about mutable types.
there's no obvious point in doing this. a c style cast is not like other languages - it is a typecast which the address on the left will be identical to the address on the right. cftypes will not throw or return null if you do a bad cast (unlike other languages). iow, it's merely a decoration for you to specify a type, and a c compiler will assume your cast is valid.
or perhaps you can provide a better example of how you would use this, if that did not help.
Update
ok. since you tagged it objc++, i'd just create a helper class which had plenty of diagnostics and did all the noisy conversions (minimal illustration):
class t_helper {
public:
t_helper(CFTypeRef cf) : d_cf(cf), d_type(CFGetTypeID(cf)) { assert(this->d_cf); }
~t_helper() {}
/* type info */
bool isString() const { return CFStringGetTypeID() == this->type(); }
CFStringRef string() { assert(this->isString()); return this->cf_cast<CFStringRef>(); }
bool isDictionary() const { return CFDictionaryGetTypeID() == this->type(); }
CFDictionaryRef dictionary() { assert(this->isDictionary()); return this->cf_cast<CFDictionaryRef>(); }
...
/* and a trivial example of an operation */
void appendMutableCopyToArray(CFMutableArrayRef array) {
if (this->isString()) {
CFMutableStringRef cp(CFStringCreateMutableCopy(0,0,this->string()));
CFArrayAppendValue(array, cp);
CFRelease(cp);
}
...
}
...
private:
template < typename T > T cf_cast() { return reinterpret_cast<T>(this->d_cf); }
const CFTypeID type() const { return this->d_type; }
private:
CFTypeRef d_cf;
const CFTypeID d_type;
};
that's about as accurate as i can get get without a really specific example of the program you are dealing with.