FAQ Database Discussion Community


Efficiently transferring elements between arrays

javascript,arrays,optimization,memory-management,data-structures
I have several JavaScript arrays, each containing a list of pointers to objects. When an object meets a certain condition, its pointer must be removed from its current containing array and placed into a different array. My current (naive) solution is to splice out the exiting array elements and concatenate...

How can I minimize this function in R?

r,function,optimization,mathematical-optimization
I'm attempting to write a formula that will determine a value of a that minimizes the function output myfun (i.e. a-fptotal). MWE: c <- as.matrix(c(.25,.5,.25)) d <- as.matrix(c(10000,12500,15000)) e <- 700 f <- 1.1 tr <- .30 myfun <- function(a) { b <- max(a-e,0) df <- data.frame(u1=c(c*b*.40),u2=c(c*b*.60)) df$year <- 1:nrow(df)...

use empty() or just use > in php which is the fastest way

php,optimization
I am trying to check the value of a variable if it is not NULL nor 0 to show its value $saleprice = $product["product_details"][0]->salePrice; I know that using if(!empty($saleprice) ) echo " on sale , sale price : $saleprice "; or if((int)$saleprice > 0) echo " on sale , sale...

Better way to check if subdomain exists without using database query or hosts file

php,apache,symfony2,optimization,wildcard-subdomain
I'm using symfony2 and in my application for student accommodation, i'm creating dynamic subdomains for each university, i'm configuring the virtual host with the wildcard subdomain entry so any subdomain would be valid. How do i check if a subdomain is registered and belongs to a university, and how do...

make all elements in list equal with minimal cost

list,optimization,prolog
I am trying to create a prolog program that allows to convert a list into a list with the same length consisting of only 1 element from the original list. This element must be chosen in such a way that a minimal number of elements from the original list needs...

Django query is slow, optimize

jquery,mysql,sql,django,optimization
def search(request): found_entries = None query = Q(feedstock__fs_name__icontains=corn found_entries = Sample.objects.filter(query).exclude(status_id=3).order_by('id') queries = request.GET.copy() sample = paging(request, found_entries) return render_to_response('search_results.html', {'sample': sample, 'queries': queries}, context_instance=RequestContext(request)) This returns about 9000 entries, it takes a very long time to query. And for the paging, if you click next page, it takes just...

Optimizing point - circle distance method

python,opencv,numpy,optimization,cython
I'm implementing a RANSAC algorithm for circle detection in images. I profiled the execution and I get: 13699392 function calls in 799.981 seconds Random listing order was used ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 {time.time} 579810 0.564 0.000 0.564 0.000 {getattr} 289905 2.343 0.000 8.661...

How to make faster queries on my mysql table?

mysql,optimization,query-optimization
I have the following table As you can see It has 1868155 rows. I am attempting to make a realtime graph, but It is impossible since almost any query lasts 1 or 2 seconds. For example, this query SELECT sensor.nombre, temperatura.temperatura FROM sensor, temperatura WHERE sensor.id = temperatura.idsensor ORDER BY...

Why do we need to put the *.odex files under /system/app even if we already have /data/dalvik-cache?

android,optimization,virtual-machine,loader,dalvik
For instance, we have phone.apk and phone.odex under /system/app. According to some unofficial documentation, phone.odex is used to expedite the process of loading an app. However, why do we not just put phone.odex under /data/dalvik? What's more weird is: There exists a file named [email protected]@[email protected] under /data/dalvik, when the app...

Delivery optimization with limits

algorithm,optimization
I have the following problem to solve: There are N cities. Each of them has some count of test samples which are needed to be processed in laboratories (labs). There are M labs. They process samples, but each has limits. We need to process all the samples. Optimization by the...

How to write Max(L)<1 without using MAX func in MATLAB

matlab,optimization,max
I have an optimization problem which is solved with fmincon. In this problem I have a constraint that says every element of the vector L must be less than or equal to 1. So basicaly I can add this constraint like this C=max(L)-1 ; % C(X)<0 But now I want...

Is there a more efficient way to solve this?

python,python-2.7,optimization,matrix
Consider the following N × N matrices A and B that contain only positive integers: B is created from A by summing the odd numbers that neighbour each element, at position [i,j] in A. Each computed sum is then stored in the corresponding position [i,j] in B. For example: At...

Compiling SCIP: 'spxsolver.h' file not found

optimization,scip
I am trying to compile SCIP using the following command: make ZLIB=false READLINE=false GMP=false Anyone has idea how to handle this issue? -> compiling obj/O.darwin.x86_64.gnu.opt/lib/objscip/objsepa.o -> compiling obj/O.darwin.x86_64.gnu.opt/lib/objscip/objvardata.o -> generating library lib/libobjscip-3.1.1.darwin.x86_64.gnu.opt.a -> compiling obj/O.darwin.x86_64.gnu.opt/lib/lpi/lpi_spx.o src/lpi/lpi_spx.cpp:76:10: fatal error: 'spxsolver.h' file not found #include "spxsolver.h" ^ 1 error generated. make[1]: ***...

Algorithms for minimizing single-variable functions

algorithm,optimization,numerical-methods
Given a continuous, convex single-variable function that I want to minimize over a bounded interval [a,b], what options do I have? I have access to the numerical derivative, but not the analytic derivative. This is done inside a loop that will be run an arbitrarily large number of times so...

One-dimensional binpacking algorithm with relative costs

algorithm,optimization,bin-packing
I'm wondering how to solve "One-dimensional binpacking problem with relative costs". We pack N volumes (with given sizes) into M bins (with given capacities) and have the matrix (NxM) of costs of each volume per each bin. So, the total cost should be minimized. Can you advice any algorithm for...

nuZ: Use of soft-assertions with weights and ids

optimization,z3
When playing around with nuZ I stumbled upon this: (declare-fun x () Int) (declare-fun y () Int) (assert-soft (= x 1) :weight 1 :id first) (assert-soft (= y 4) :weight 3 :id first) (assert-soft (= x 2) :weight 1 :id second) (assert-soft (= y 5) :weight 3 :id second) (assert-soft...

Disabling fp-model strict when using ifort with f2py

python,numpy,optimization,fortran,f2py
I'm using f2py to offload performance critical sections of my python code to fortran. I have two fortran compilers, gfortran and ifort. Since the code I run will be on intel processors, ifort is usually faster. But for the most critical part of my code, I observe the opposite, with...

Prefetching double class member requires casting to char*?

c++,performance,optimization,x86,prefetch
I have a class which I am using _mm_prefetch() to pre-request the cacheline containing a class member, of type double: class MyClass{ double getDouble(){ return dbl; } //other members double dbl; //other members }; _mm_prefetch() signature is: void _mm_prefetch (char const* p, int i) But when I do: _mm_prefetch((char*)(myOb.getDouble()), _MM_HINT_T0);...

How can I efficiently create unique relationships in Neo4j?

optimization,neo4j,cypher
Following up on my question here, I would like to create a constraint on relationships. That is, I would like there to be multiple nodes that share the same "neighborhood" name, but each uniquely point to a particular city in which they reside. As encouraged in user2194039's answer, I am...

Can I use the “null pointer optimization” for my own non-pointer types?

optimization,rust
When you have an Option<&T>, the compiler knows that NULL is never a possible value for &T, and encodes the None variant as NULL instead. This allows for space-saving: use std::mem; fn main() { println!("{}", mem::size_of::<&u8>()); // 8 on 64-bit println!("{}", mem::size_of::<Option<&u8>>()); // 8 on 64-bit assert_eq!(mem::size_of::<&u8>(), mem::size_of::<Option<&u8>>()); } However,...

Perform integer division using multiplication

assembly,optimization,bit-manipulation,division,multiplication
Looking at x86 assembly produced by a compiler, I noticed that (unsigned) integer divisions are sometimes implemented as integer multiplications. These optimizations seem to follow the form value / n => (value * ((0xFFFFFFFF / n) + 1)) / 0x100000000 For example, performing a division by 9: 12345678 / 9...

How to efficiently select neighbour in 1-dimensional and n-dimensional space for Simulated Annealing

java,algorithm,search,optimization,simulated-annealing
I would like to use Simulated Annealing to find local minimum of single variable Polynomial function, within some predefined interval. I would also like to try and find Global minimum of Quadratic function. Derivative-free algorithm such as this is not the best way to tackle the problem, so this is...

OpenCV FAST corner detection SSE implementation walkthrough

c,performance,opencv,optimization,sse
Could someone help me understanding the SSE implementation of the FAST corner detection in OpenCV? I understand the algorithm but not the implementation. Could somebody walk me through the code? The code is long, so thank you in advance. I am using OpenCV 2.4.11 and the code goes like this:...

Minimize a function with two variables

r,optimization
I would like to minimize a function with two variables. First I have made a function (rba), which is needed inside the function (kvasum) that I need to minimize. The values to minimized over are a part of rba. # Data vpk = data.frame(V1 =c(3650000000, 19233, 2211.2, 479.47, 168.46, 83.447,...

In general, how expensive is calling an external program?

optimization,external
I know external programs can be called, but I don't know how expensive it is compared to, say, calling a subroutine. By the cost of calling, I mean the overhead of starting the program, rather than the cost of executing the program's code itself. I know the cost probably varies...

How configure Stanford QNMinimizer to get similar results as scipy.optimize.minimize L-BFGS-B

java,optimization,machine-learning,scipy,stanford-nlp
I want to configurate the QN-Minimizer from Stanford Core NLP Lib to get nearly similar optimization results as scipy optimize L-BFGS-B implementation or get a standard L-BFSG configuration that is suitable for the most things. I set the standard paramters as follow: The python example I want to copy: scipy.optimize.minimize(neuralNetworkCost,...

How to interpret the output of the CPLEX interactive optimizer?

optimization,cplex
I have been using the CPLEX interactive optimizer to solve some linear programming problems. I generate the problem, use the read command from CPLEX, and then run optimize. For some problems, CPLEX produces a solution within an hour and I use write <filename> sol to obtain the complete solution. For...

Understanding Lingo derived sets

optimization,lingo
I am completely new to LINGO and I found this example in LINGO. MODEL: ! A 6 Warehouse 8 Vendor Transportation Problem; SETS: WAREHOUSES / WH1 WH2 WH3 WH4 WH5 WH6/: CAPACITY; VENDORS / V1 V2 V3 V4 V5 V6 V7 V8/ : DEMAND; LINKS( WAREHOUSES, VENDORS): COST, VOLUME; ENDSETS...

Optimization: memcached vs mysql memory

php,mysql,optimization
I am developing highload application, and thinking whether to use memcache or mysql memory table. Table is tiny, not more than 30-40 rows and in most cases the application reads them all at once. (like select * from table and fetches all rows) May be someone has information about how...

Optimizing Ansible Transport\SSH for Unconventional Networks

networking,optimization,ssh,ansible
I'm wondering how to optimise Ansible to work with a network radically different to one where use cases where Accelerate and default might not necessarily be beneficial. In this scenario I'm not dealing with a virtual network, nor am I dealing with servers. I'm dealing with hundreds of embedded, with...

Placing Limits on Optim

r,optimization,regression,rscript
i'm trying to use an algorithm to minimise the least squares of models. I'd like to be able to confine all the parameters to within sensible ranges however when i run this script for whatever reason it is disregarding my limits. More of a debugging issue than anything else. Any...

Optimizing two-dimensional arrays

python,arrays,optimization,multidimensional-array,list-comprehension
I'm coding in Python 2.7. I have two 2D arrays of coordinate tuples. array1 = [[[00_RA,00_DEC] [01_RA,01_DEC] ... [0N_RA,0N_DEC]] [[10_RA,10_DEC] [11_RA,11_DEC] ... [1N_RA,1N_DEC]] ... [[M0_RA,M0_DEC] [M1_RA,M1_DEC] ... [MN_RA,MN_DEC]]] array2 = [[[00_ra,00_dec] [01_ra,01_dec] ... [0n_ra,0n_dec]] [[10_ra,10_dec] [11_ra,11_dec] ... [1n_ra,1n_dec]] ... [[m0_ra,m0_dec] [m1_ra,m1_dec] ... [mn_ra,mn_dec]]] I want to find the coordinates of...

Fair timing of two equivalent functions with -O3

c++,optimization,timing
A coworker sent me some interesting code the calculates the index of the LSB of an integer: unsigned int v; // the input number int r; // result goes here static const int MultiplyDeBruijnBitPosition[32] = { 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17,...

Minimum difference between sum of two numbers in an array

c++,algorithm,optimization,dynamic-programming
I am trying to solve this problem: A Professor of Physics gave projects to the students of his class. The students have to form a team of two for doing the project. The professor left the students to decide the teams. The number of students in a class will be...

How can I optimize filename generator with underscore?

python,optimization
I have this code def filename_generator(name, path=''): names = [] for i in range(len(name)): p = '_'.join([x for x in name[i:]]) + path names.append(name[:i] + p) names += filename_generator(name[:i], p) return sorted(list(set(names))) for e in filename_generator('longlonglonglonglonglongname'): print(e) How can you see, i need generate all combinations of filename with underscore...

Better to declare JavaScript Object inside for loop or outside in terms of time optimization

javascript,arrays,optimization,variable-declaration
Edit: This question is mainly focussed on should objects be declared inside a for loop (huge loop of an order of billion count) in each iteration or is it better to declare the object once outside for loop to save time during object declaration (time spent on memory allocation) in...

Alpha blending using table lookup is not as fast as expected

c,performance,optimization,alphablending,lookup-tables
I thought memory access would be faster than the multiplication and division (although compiler-optimized) done with alpha blending. But it wasn't as fast as expected. The 16 megabytes used for the table is not an issue in this case. But it is a problem if table lookup could even be...

How can I extract part of a PChar into a string?

string,delphi,optimization,pchar
During profiling I came across a function that was taking quite a bit of time, but essentially boiled down to this very simple piece of code: function GetSubstring(AInput: PChar; AStart, ASubstringLength: Integer): string; begin Result := Copy(AInput, AStart, ASubstringLength); end; This function returns the expected sub-string, but it doesn't scale...

CSSRules group selectors with common properties

javascript,jquery,html,css,optimization
This script when included in an HTML document which includes any declared styles (excluding those set by style="") will output an optimized stylesheet to the to the page. The script uses the following methods... Ignore any @ or : rules to leave responsive styles as is. Separate the rules into...

Optimizing a large if-else branch with binary search

c,optimization,binary-search,linear-search
So there is an if-else branch in my program with about 30 if-else statements. This part runs more than 100 times per second, so I saw it as an opportunity to optimize, and made it do binary search with a function pointer array (practically a balanced tree map) instead of...

Ackley optimization Matlab

matlab,optimization,strategy
Can anyone help me please with how should i do an optimaztion with Evolution Strategies for ackley function ? Here i have the function: function rez=ackley(x) [m,d]=size(x); sum1=0; sum2=0; for i=1:d sum1=sum1+x(i)^2; sum2=sum2+cos(2*pi*x(i)); end rez=20+exp(1)-20*exp(-0.1*sqrt(sum1/d))-exp(sum2/d); end ...

Picking Ad Mob Mediation Networks 2015

optimization,admob
Looking to setup network mediation on AdMob. There are a lot of networks on the list - so I'm looking for some sort of comparison of the networks or recommendations on setting up mediation such as: how many networks to use etc... I plan to utilize simple 320x50 ad banner...

When compiled with -O2, program skips assignment

c++,optimization
I was writing a code to solve a programming challenge, but when I submitted the code it was giving a runtime error. Someone told me to try compiling it using -O2 to see if I could locate the issue. Turns out that something really creepy happens: when executed, the optimized...

glclearcolor best color?

opengl,optimization
this might seam like a stupid question but i was wondering, when calling glClear(GL11.GL_COLOR_BUFFER_BIT); glClearColor(1, 0, 0, 1); to clear the screen in my opengl project is there any performance differences for using different colors? i mean if for example i clear to red vs blue/green/*insert any color will it...

Loop unrolling in inlined functions in C

c,optimization,inline,icc
I have a question about C compiler optimization and when/how loops in inline functions are unrolled. I am developing a numerical code which does something like the example below. Basically, my_for() would compute some kind of stencil and call op() to do something with the data in my_type *arg for...

Does LINQ make use of underlying data structure?

c#,linq,optimization
Take a look for example at the accepted answer here Which method performs better: .Any() vs .Count() > 0?. Now I wonder if LINQ functions (e.g. Last, FirstOrDefault) are completely naive and all they do is enumerating/checking IEnumerable or they check what data structure is beneath (at least for basic...

Inline function at -O0 causes link failure in clang [duplicate]

c,optimization,clang,inline,c99
This question already has an answer here: Is “inline” without “static” or “extern” ever useful in C99? 3 answers I'm trying to compile the following code with clang at various optimization levels: #include <stdio.h> inline int foo() { return 42; } int main() { printf("%d\n", foo()); } At -O1,...

efficient way of passing Data between Matlab functions

matlab,function,optimization,parameter-passing
I am solving a very large optimization problem. The objective function and constraint function needs numerous data. Currently I am passing the data as structure to them. myFS(X,Dat,g_Index, f_Index) % Dat is a structure which includes many variables Do you think, it's an efficient way to reduce the elapsed time?...

How minimal can an SVG be?

optimization,svg
I just reduced this SVG: <?xml version="1.0" standalone="no"?> <svg viewBox="0 0 480 150" style="background-color:#ffffff00" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" x="0px" y="0px" width="480" height="150"> <path d="M 0 35.5 L 6.5 22.5 L 16 37 L 23 24 L 34.8 43.7 L 42.5 30 L 50.3 47 L 59.7 27.7 L 69 47...

Which way of setting fields value is better and why?

java,optimization,constructor
This question can be stupid, but I just want to know, is there any difference? class A{ // common code private int field; public void setField(int field){ this.field = field; } //way 1 public A(int field){ this.field = field; } //way 2 public A(int field){ setField(field); } } ...

Getting the maximum sum of pairs' second elements given weight limitation on the first elements

java,algorithm,sorting,optimization
I'm looking at example interview questions and this popped up. The question asks for a program that takes in two numbers, L (limit) and C (number of cases to be input). Afterwards, C amount of integer pairs are input, where the pair consists of (weight, value). Now, the program should...

Java: Assigning a variable its current value?

java,variables,optimization,value
If I have a string that is currently empty String s = ""; and reassign it s = ""; is it bad it I don't do it like this? if(!s.isEmpty()){ s = ""; } or will the compiler pick up on it and optimize for me?...

Dynamic programming: how to design algorithm for when there are two factors to consider?

algorithm,optimization,dynamic-programming,frequency
I have the following problem and I only have a slight idea about it: Consider a tape storage problem. Given n files of length l1,...,ln and frequencies with which they are accessed f1,...,fn, where sum of all frequencies is 1 and 0<fi<1. "Optimal" means to minimize the average retrieval time...

C++ Optimization breaking OLE Automation program (non-MFC)

c++,optimization,visual-studio-2013,ole,office-automation
I'm writing a program to parse a Word Document and export data out to an Excel Workbook using OLE Automation (the non-MFC way I guess). Works fine in Debug, not so in Release (specifically if optimization is enabled). The error is that the IDispatch::Invoke call failed, specifically: 0x80020004 DISP_E_PARAMNOTFOUND Parameter...

FastDOM - Read / write every 17ms?

javascript,dom,optimization,asynchronous,requestanimationframe
FastDOM - a small library that batches DOM reads & writes into raf (requestAnimationFrames). https://github.com/wilsonpage/fastdom I have read the code, however, I am struggling to understand how it works. Here are a few presumptions we have: - Browsers are generally set to 60fps - So in total, there can be...

How to shorten `if-statement`

php,loops,optimization
I have an if statement in my foreach loop. The condition is about 125 characters long. Are there other ways to shorten this? if ($col == 'foo' || $col == 'bar' || $col == 'baz' || $col == 'fubar' || $col == 'spam' || $col == 'eggs') { continue; }...

NumPy: How to avoid this loop?

python,numpy,optimization
Is there a way to avoid this loop so optimize the code? import numpy as np cLoss = 0 dist_ = np.array([0,1,0,1,1,0,0,1,1,0]) # just an example, longer in reality TLabels = np.array([-1,1,1,1,1,-1,-1,1,-1,-1]) # just an example, longer in reality t = float(dist_.size) for i in range(len(dist_)): labels = TLabels[dist_ ==...

Matlab @fminunc objective function optimization

matlab,function,optimization,maximize
I am currently practicing a simple function optimization in Matlab and hope you could provide with little assistance / explanation on the following error: %quadramin.m function z=quadramin(param,data); z=data.*(param(1).^2 - param(2).^3)+3; %quadramin_lik.m function quadlik = quadramin_lik(param,data); %pseudo/ad-hoc log-likelihood function quadlik = quadramin(param,data)- 10; %script.m data=trnd(5,6,1); param0=[2,3]; [param_eq,exitflag,output,grad,hessian] = ... fminunc(@(param) quadramin_lik(param,data),param0)...

More efficient way to get nearest center

python,numpy,optimization
My data object is an instance of: class data_instance: def __init__(self, data, tlabel): self.data = data # 1xd numpy array self.true_label = tlabel # integer {1,-1} So far in code, I have a list called data_history full with data_istance and a set of centers (numpy array with shape (k,d)). For...

Brent's method in the R optim implementation always returns the same local minimum

r,optimization
I'm trying to minimise the function shown above. I'm searching between (-1,1). I use the following code optim(runif(1,min=-1,max=+1), ..., method = "Brent", lower = -1.0, upper = 1.0) and I've noticed that it always returns a value of x = -0.73 instead of the correct x = 0.88 answer....

Optimizing a sub-sub-query in MySQL

mysql,optimization,subquery
I have a request ticketing system that allows for commenting on the tickets. I've added a feature that shows the user upon login the most recent comment to any of their tickets as kind of a clue if anything has changed since their last visit. I can accomplish this with...

weird optimization (remove a function) in GCC

c,gcc,optimization
I met a weird optimization in GCC 4.8.2 with -O2, which removes a function. See the following code. increase() and increase2() are same except that there is a printf() in the latter one. However increase() is removed if using -O2 in GCC. #include <stdio.h> #include <stdint.h> #include <arpa/inet.h> void swap(uint64_t...

type conversion performance optimizable?

c#,xml,csv,optimization,type-conversion
The following snippet converts xml data to csv data in a data processing application. element is a XElement. I'm currently trying to optimize the performance of the application and was wondering if I could somehow combine the two operations going on below: Ultimately I still want access to the string...

code optimising for if-else function

c++,optimization
I want to write a partition function. The output values are obtained by comparing the values of input dx and dy. The below code run very slow. Any suggestion to speedup the code? I search the web, it seems that using lookup table or SSE instructions is possible. But I...

How to load all symbols from shared library on start up?

c,linux,optimization,shared-libraries,glibc
Good day! I have a fork-on-connect daemon. After profiling it with perf tool, I found out that function "do_lookup_x" consume lot's of CPU time. All the function calls for shared-libraries functions are after fork. Is there any way to lookup all symbols before fork?...

Add a python flag cx_freeze to executable

python,optimization,distribution,cx-freeze,pyglet
I'm making a game using pyglet, which runs like a tortoise (~30-35 FPS) unless I pass the -O flag to python when running it (which gives me a smooth 60FPS). I'm planning on using cx_freeze to distribute it, but I need the -O flag to be used every time the...

HackerEarth Probelm: Reverse Primes

java,optimization,out-of-memory,primes
Generate as many distinct primes P such that reverse (P) is also prime and is not equal to P. Output: Print per line one integer( ≤ 10^15 ). Don't print more than 10^6 integers in all. Scoring: Let N = correct outputs. M = incorrect outputs. Your score will...

PageSpeed Insights : Load css files after the closing

html,css,optimization
Google Page insight tells us to optimize CSS file like this : Vous pouvez alors incorporer le code CSS essentiel comme ceci : <html> <head> <style> .blue{color:blue;} </style> </head> <body> <div class="blue"> Hello, world! </div> </body> </html> <link rel="stylesheet" href="small.css"> source : https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery The French link is https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery?hl=fr I’ve never...

MatLab code speed and optimization. How to improve?

performance,matlab,function,optimization,plot
Could someone please run this for me and tell me how long it takes for you? It took my laptop 60s. I can't tell if it's my laptop that's crappy or my code. Probably both. I just started learning MatLab, so I'm not yet familiar with which functions are better...

How does GCC store member functions in memory?

c++,performance,gcc,optimization,compiler-optimization
I am trying to minimise the size my class occupies in memory (both data and instructions). I know how to minimise data size, but I am not too familiar with how GCC places member functions. Are they stored in memory, the same order they are declared in the class?...

(Java) Efficiency in my Starter Bubble Sort

java,algorithm,optimization,foreach,bubble-sort
I am new to Java and I have a question regarding optimization. How fast is it if I declare before my IF statement a variable that gets the value of x.indexOf(i) + 1 instead of just putting it twice in my code below (which depicts the first call of a...

What is the advantage of the paperboat format in performance optimization of ML?

optimization,machine-learning,dataset
The paperBoat format claims to provide a better dataset representation for machine learning routines. I'd like to understand the nature of its optimization. I understand that using an integer representation for model attributes means a faster processing of the data set, what are the other improvements. Also, how to tune...

Performing large queries on Array or DB in php? [closed]

php,mysql,arrays,performance,optimization
Suppose I have an array of 10000 users, for each user I need to store 100 last actions they did, also the time of that action. These data are stored on a mysql database too. For every second, I need to check 100 user actions, It means I need to...

SAS drop multiple variables indexed by tens

optimization,sas
My question is likely stupid but I have not found an answer yet. I have a variable var index by tens : var10, var20... var90. At some point of my code I want to drop all of them. I can do data want(drop=var10 var20 var30 var40 var50 var60 var70 var80...

nuZ: What does the model say

optimization,z3
When playing around with nuZ I stumbled upon this: (declare-fun x () Int) (declare-fun y () Int) (assert-soft (= x 1) :weight 1 :id first) (assert-soft (= y 4) :weight 3 :id first) (assert-soft (= x 2) :weight 1 :id second) (assert-soft (= y 5) :weight 3 :id second) (assert-soft...

Does compiler optimize operation on const variable and literal const number?

c#,.net,optimization
Let's say I have class with field: const double magicalConstant = 43; This is somewhere in code: double random = GetRandom(); double unicornAge = random * magicalConstant * 2.0; Will compiler optimize my code so that it doesn't calculate magicalConstant * 2.0 every time it calcuates unicornAge? I know that...

JQuery Show Hide Multiple Div Button

javascript,jquery,performance,function,optimization
I need to develop a News page with 3 articles that can be hidden or showed one by one, by means of 2 buttons: "Show more news" and "Show less news" Each article must be hidden/displayed by clicking the relevant button only once, starting from the last article (at the...

Hashmap with time values, want to find value at specific second

java,optimization
I have a Linked Hash Map (My query orders the points by time) that contains stock data from a database, the time is in (int) seconds after midnight and the values are double values in both MYSQL and Java. I have attached a sample of the data below. The amount...

Can this javascript code be cleaned up?

javascript,jquery,optimization
The code is working just fine now, but is a bit sloppy and long. I'm not as proficient in js as I would like to be. Javascript $("#IDArea1").click(function () { $('#indicator1').toggleClass("icon-caret-up icon-caret-down"); $('#indicator2').removeClass("icon-caret-up"); $('#indicator2').addClass("icon-caret-down"); $('#indicator3').removeClass("icon-caret-up"); $('#indicator3').addClass("icon-caret-down"); }); $("#IDArea2").click(function () { $('#indicator2').toggleClass("icon-caret-up icon-caret-down");...

Absolute value equality of variables in MATLAB optimization

matlab,optimization
I am trying to solve an optimization problem using either MATLAB's built-in linprog function, or with MATLAB CVX front-end. These tools provide an easy way to model constraints such as A.x <= B, Aeq.x == Beq, and a <= x <= b. I know for sure that some of my...

Speeding up a function involving mapply and integrate

r,optimization,integrate,mapply
I've inherited R some code and it runs incredibly slowly. Most of the time is spent evaluating the functions of the form (there are about 15 such functions with different integrands G): TMin <- 0.5 F <- function (t, d) { result <- ifelse(((d > 0) & (t > TMin)),...

Disable JRockit Optimzation per class

optimization,jvm-hotspot,jrockit
Is there anyway to do this? I have seen there is a -XnoOpt function, but that seems more global than only applying this to a particular class. Any help would be useful ... even if to tell me this is not possible. Thanks!...

Why is Java faster if it repeats the same code?

java,optimization,jvm,jvm-hotspot
Given the following code: public class Test{ static int[] big = new int [10000]; public static void main(String[] args){ long time; for (int i = 0; i < 16; i++){ time = System.nanoTime(); getTimes(); System.out.println(System.nanoTime() - time); } } public static void getTimes(){ int d; for (int i = 0;...

How to improve performance method GetThumbnailAsync in window phone 8.1

c#,image-processing,optimization,winrt-xaml
I write a function to show images on a folder (assume i have about 60 images in this folder) in window phone 8.1. And the problem is function GetThumbnailAsync() take so long time when i create stream to get bitmapImage. Here's my code //getFileInPicture is function get all file in...

(WHY?) Greatest+Coalesce way faster than a single select with or

mysql,sql,optimization
I'm currently having a hard time unterstanding why this: greatest( coalesce((select f.expReplDate from da_sakunden_fzg f where (f.ServerNr = k.ServerNr) and (k.proId = f.proId) order by f.expReplDate limit 1),0), coalesce((select f.expReplDate from da_sakunden_fzg f where (f.ServerNr = k.ServerNr) and (k.proId = f.ownerProId) order by f.expReplDate limit 1),0) ) as WMZ is...

Optimizing for Social Leaderboards

python,google-app-engine,optimization,twitter,leaderboard
I'm using Google App Engine (python) for the backend of a mobile social game. The game uses Twitter integration to allow people to follow relative leaderboards and play against their friends or followers. By far the most expensive piece of the puzzle is the background (push) task that hits the...

Mysql optimize to avoid table scan

mysql,sql,table,optimization,scan
Please consider the following table: _____________________ | sentence_word | |---------|---------| | sent_id | word_id | |---------|---------| | 1 | 1 | | 1 | 2 | | ... | ... | | 2 | 4 | | 2 | 1 | | ... | ... | With this table structure...

Improve Speed of Piecewise Function in MATLAB

matlab,optimization,vectorization
I have a small piecewise function that profiling reveals is taking 60% of the runtime of the program. It is called very often because it goes within some integrals that I perform quite a lot in my code. According to profiling, it is called 213560 times, taking 47.786 s in...

What is the most efficient way to perform a multiplication?

java,performance,optimization
Let's say we have to perform this calculation 10000 times in a loop. Case 1 double answer = i * 1.6712 * 1000 * 60; Case 2 double answer = i * 100272; // 1.6712 * 1000 * 60 = 100272 where i is the loop index. Question What is...

Optimization Toolbox (fmincon) - How to set logical constraints?

algorithm,matlab,optimization
Hello all :) I'm pretty new to Optimization and barely understand it (was about ready to slit my wrist after figuring out how to write Objective Functions without any formal learning on the matter), and need a little help on a work project. How would I go about setting a...

How do i pass input variable to a C++ class method invoked in many places based on user input?

c++,optimization
I have a file with multiple independent C-style functions defined in it ,wherein, each function instantiates a class and invokes a method of that class with certain parameters. I need to take input from the user on what function to call , and what parameter to send in that method....

Optimal Flow Distribution

algorithm,optimization,network-flow
I've searched stackoverflow and google but I haven't found someone with quite the same type of problem. Optimal distribution of power plants on a city seemed like the closest solution to this problem but I believe my problem is simplier than the question there and therefore would have a better...

Eager Loading Optimization in ruby on rails

ruby-on-rails,ruby,optimization,query-optimization
I have a product that has_many Variants. And a variant belongs to a product. I want to display the name of the product(which can be found in Product) and the price and quantity(which can be found in Variants). Product table: -id -title -description Variants table: - id - is_active(boolean) -...

R: NaNs produced in Log-Likelihood optimisation

r,optimization
Evening stackoverflow- community, I am working on identifying svar models and do have some questions about the following looklikehood function http://imgur.com/msJZkB4 We want to estimate the values of B_22, which is a 2x2 matrix, and Omega (in my code I call this matrix „L“), which has the unkown parameters on...

optimization algorithm for circular data

r,optimization,circular,maximization
Background: I am interested in localizing a sound source from a suite of audio recorders. Each audio array consists of 6 directional microphones spaced evenly every 60 degrees (0, 60, 120, 180, 240, 300 degrees). I am interested in finding the neighboring pair of microphones with the maximum set of...

Optimization - is union the best way to go in this case?

sql-server,join,optimization,union
I have a dataset which is updated on a daily basis from an external data source (Example). This data is then combined with some other in-house data (Scale) and is formed to a new table. Example contains some figures that can be errornous at times. I register for which funds...

Vary coefficient in system of equation in Matlab's fsolve

matlab,optimization
I want to solve the following two equations using fsolve: p*x(1) - x(2) - exp(-x(1))=0 .... (1) -x(1) + 2*x(2) - exp(-x(2))=0.....(2) where "p" is the coefficient that I want to vary from -3 to +3, i.e., -3:0.1:3. This works if the value of p is manually specified each time,...

Optimizing a simple linear curve (constant and coefficient estimated from a regression)

r,optimization
I am trying to calculate the turning point of a a few functions where I have estimated the coefficient and constant from a regression. I'm using the optimize function for this as my curves are all linear. My function looks like: F<- function(x){ beta* x + alpha } mind: beta...

Optimal Compare Algorithm for finding string matches in List of strings C#

c#,string,algorithm,optimization,language-agnostic
Say I have a list of 100,000 words. I want to find out if a given string matches any words in that list, and I want to do it in the fastest way possible. Also I want to know if any other words, that are formed by starting with the...

Slow start-up of large programs

windows,optimization,loading
The following program #include <stdio.h> int main() { static char a[1 << 28] = {1}; printf("%d\n", a[0]); return 0; } Compiles on Windows 7 x64 to this executable 19/06/2015 21:57 268,519,936 a.exe Which takes 5.6 seconds to run, even when run several times in succession to make sure it's cached...