The following code ran perfectly in my DEV-C++ compiler but when I submitted in codechef, after running for 3-4 seconds it shows "SIGABRT ERROR". I have researched on this error and have done everything i could to debug, but even after a week I am not able to. Please Help !! Thanks in advance.
For reference question is http://www.codechef.com/problems/LOWSUM
enter code here
void selsort(long long *ssum,long long len)
{
long long low;
for(long long i=0;i<len;i++)
{
low = ssum[i];
long long pos=i;
for(int j=i+1;j<len;j++)
{
if(ssum[j]<low)
{
low = ssum[j];
pos = j;
}
}
ssum[pos] = ssum[i];
ssum[i] = low;
}
}
int main()
{
int t,k,q;
cin>>t;
for(int i=0;i<t;++i)
{
cin>>k;
cin>>q;
long long sq = k*k;
long long *mot=NULL,*sat=NULL;
mot = new long long [k];
sat = new long long [k];
long long *sum = new long long[sq];
long long qth;
long long b=0;
for(int j=0;j<k;++j)
{
cin>>mot[j];
}
for(int j=0;j<k;++j)
{
cin>>sat[j];
}
for(int j=0;j<k;++j)
{
for(int a=0;a<k;++a)
{
sum[b] = mot[a]+sat[j];
++b;
}
}
selsort(sum,sq);
for(int j=0;j<q;++j)
{
cout<<"\n";
cin>>qth;
cout<<"\n"<<sum[qth-1];
}
delete []sum;
delete []mot;
delete []sat;
}
return 0;
}
SIGABRT signal is sent due to many reasons quoting codechef
SIGABRT errors are caused by your program aborting due to a fatal error. In C++, this is normally due to an assert statement in C++ not returning true, but some STL elements can generate this if they try to store too much memory.
In your case it seems to be use of excessive memory
mot = new long long [k];
sat = new long long [k];
long long *sum = new long long[sq];
Note that the value of k can be as large as 20000 so declaring a array of size k will be fine but your sq = k*k which is of order of 4*10^8 which is causing a out of memory problem memory. And your algorithm is also not good enough to give AC within time limit.
Codechef has its own forum to ask such questions, and preferable ways to solve this problem has already been discussed there
http://discuss.codechef.com/problems/LOWSUM
Related
I have a List of a custom CallRecord objects
public class CallRecord {
private String callId;
private String aNum;
private String bNum;
private int seqNum;
private byte causeForOutput;
private int duration;
private RecordType recordType;
.
.
.
}
There are two logical conditions and the output of each is:
Highest seqNum, sum(duration)
Highest seqNum, sum(duration), highest causeForOutput
As per my understanding, Stream.max(), Collectors.summarizingInt() and so on will either require several iterations for the above result. I also came across a thread suggesting custom collector but I am unsure.
Below is the simple, pre-Java 8 code that is serving the purpose:
if (...) {
for (CallRecord currentRecord : completeCallRecords) {
highestSeqNum = currentRecord.getSeqNum() > highestSeqNum ? currentRecord.getSeqNum() : highestSeqNum;
sumOfDuration += currentRecord.getDuration();
}
} else {
byte highestCauseForOutput = 0;
for (CallRecord currentRecord : completeCallRecords) {
highestSeqNum = currentRecord.getSeqNum() > highestSeqNum ? currentRecord.getSeqNum() : highestSeqNum;
sumOfDuration += currentRecord.getDuration();
highestCauseForOutput = currentRecord.getCauseForOutput() > highestCauseForOutput ? currentRecord.getCauseForOutput() : highestCauseForOutput;
}
}
Your desire to do everything in a single iteration is irrational. You should strive for simplicity first, performance if necessary, but insisting on a single iteration is neither.
The performance depends on too many factors to make a prediction in advance. The process of iterating (over a plain collection) itself is not necessarily an expensive operation and may even benefit from a simpler loop body in a way that makes multiple traversals with a straight-forward operation more efficient than a single traversal trying to do everything at once. The only way to find out, is to measure using the actual operations.
Converting the operation to Stream operations may simplify the code, if you use it straight-forwardly, i.e.
int highestSeqNum=
completeCallRecords.stream().mapToInt(CallRecord::getSeqNum).max().orElse(-1);
int sumOfDuration=
completeCallRecords.stream().mapToInt(CallRecord::getDuration).sum();
if(!condition) {
byte highestCauseForOutput = (byte)
completeCallRecords.stream().mapToInt(CallRecord::getCauseForOutput).max().orElse(0);
}
If you still feel uncomfortable with the fact that there are multiple iterations, you could try to write a custom collector performing all operations at once, but the result will not be better than your loop, neither in terms of readability nor efficiency.
Still, I’d prefer avoiding code duplication over trying to do everything in one loop, i.e.
for(CallRecord currentRecord : completeCallRecords) {
int nextSeqNum = currentRecord.getSeqNum();
highestSeqNum = nextSeqNum > highestSeqNum ? nextSeqNum : highestSeqNum;
sumOfDuration += currentRecord.getDuration();
}
if(!condition) {
byte highestCauseForOutput = 0;
for(CallRecord currentRecord : completeCallRecords) {
byte next = currentRecord.getCauseForOutput();
highestCauseForOutput = next > highestCauseForOutput? next: highestCauseForOutput;
}
}
With Java-8 you can resolved it with a Collector with no redudant iteration.
Normally, we can use the factory methods from Collectors, but in your case you need to implement a custom Collector, that reduces a Stream<CallRecord> to an instance of SummarizingCallRecord which cotains the attributes you require.
Mutable accumulation/result type:
class SummarizingCallRecord {
private int highestSeqNum = 0;
private int sumDuration = 0;
// getters/setters ...
}
Custom collector:
BiConsumer<SummarizingCallRecord, CallRecord> myAccumulator = (a, callRecord) -> {
a.setHighestSeqNum(Math.max(a.getHighestSeqNum(), callRecord.getSeqNum()));
a.setSumDuration(a.getSumDuration() + callRecord.getDuration());
};
BinaryOperator<SummarizingCallRecord> myCombiner = (a1, a2) -> {
a1.setHighestSeqNum(Math.max(a1.getHighestSeqNum(), a2.getHighestSeqNum()));
a1.setSumDuration(a1.getSumDuration() + a2.getSumDuration());
return a1;
};
Collector<CallRecord, SummarizingCallRecord, SummarizingCallRecord> myCollector =
Collector.of(
() -> new SummarizinCallRecord(),
myAccumulator,
myCombiner,
// Collector.Characteristics.CONCURRENT/IDENTITY_FINISH/UNORDERED
);
Execution example:
List<CallRecord> callRecords = new ArrayList<>();
callRecords.add(new CallRecord(1, 100));
callRecords.add(new CallRecord(5, 50));
callRecords.add(new CallRecord(3, 1000));
SummarizingCallRecord summarizingCallRecord = callRecords.stream()
.collect(myCollector);
// Result:
// summarizingCallRecord.highestSeqNum = 5
// summarizingCallRecord.sumDuration = 1150
You don't need and should not implement the logic by Stream API because the tradition for-loop is simple enough and the Java 8 Stream API can't make it simpler:
int highestSeqNum = 0;
long sumOfDuration = 0;
byte highestCauseForOutput = 0; // just get it even if it may not be used. there is no performance hurt.
for(CallRecord currentRecord : completeCallRecords) {
highestSeqNum = Math.max(highestSeqNum, currentRecord.getSeqNum());
sumOfDuration += currentRecord.getDuration();
highestCauseForOutput = Math.max(highestCauseForOutput, currentRecord.getCauseForOutput());
}
// Do something with or without highestCauseForOutput.
I want to read the last message written to a SingleChronicleQueue instance.
While "chronicle.createTailer().direction(TailerDirection.BACKWARD).toEnd()" works while we are on the same cycle as the last written message, as soon as we are in one of the future cycles (compared to the last written message), tailer.readDocument(...) always returns "false".
I have implemented a test to reproduce the issue based on the SingleChronicleQueueTest.testForwardFollowedBackBackwardTailer test:
#Test
public void testForwardFollowedBackBackwardTailer() {
File tmpDir = getTmpDir();
// when "forwardToFuture" flag is set, go one day to the future
AtomicBoolean forwardToFuture = new AtomicBoolean(false);
TimeProvider timeProvider = () -> forwardToFuture.get()
? System.currentTimeMillis() + Duration.ofDays(1).toMillis()
: System.currentTimeMillis();
try (RollingChronicleQueue chronicle = SingleChronicleQueueBuilder.binary(tmpDir)
.rollCycle(TEST2_DAILY)
.wireType(this.wireType)
.timeProvider(timeProvider)
.build()) {
ExcerptAppender appender = chronicle.acquireAppender();
int entries = chronicle.rollCycle().defaultIndexSpacing() + 2;
for (int i = 0; i < entries; i++) {
int finalI = i;
appender.writeDocument(w -> w.writeEventName("hello").text("world" + finalI));
}
// go to the future (and to the next roll cycle)
forwardToFuture.set(true);
for (int i = 0; i < 3; i++) {
readForward(chronicle, entries);
readBackward(chronicle, entries);
}
}
}
After these changes to the "testForwardFollowedBackBackwardTailer" method,
the test fails at assertTrue(documentContext.isPresent()) line in the "readBackward" method.
Is there any way to reliably read the last message from SingleChronicleQueue instance, no matter how far in the past the last message is? (without reading through the whole chronicle instance from the start)
Which version are you using as this should work. If you have the latest version, it is a bug.
Can you submit a pull request with this unit test?
I am very new in kernel coding. My question might seem very silly but I have spent quite amount of time and couldn't figure out what I am doing wrong.
here is my code. It seems like nothing gets copied to buff and when I printk result_of_cfu, it is 8 meaning 8 bytes are not copied.
what am I doing wrong here?
asmlinkage long sys_take_stat(struct array_stats *stats, long data[],long size){
unsigned long result_of_cfu = 0;
int counter = 0;
for(counter = 0;counter<size;size++){
long buff = 0;
long current_data = data[counter];
result_of_cfu = copy_from_user(&buff,¤t_data,sizeof(current_data));
}
}
You should use copy_from_user instead of dereferencing data pointer:
...
for(counter = 0;counter<size;size++){
long buff;
result_of_cfu = copy_from_user(&buf, data + counter, sizeof(*data));
}
I am trying to instrument java synchronized block using ASM. The problem is that after instrumenting, the execution time of the synchronized block takes more time. Here it increases from 2 msecs to 200 msecs on Linux box.
I am implementing this by identifying the MonitorEnter and MonitorExit opcode.
I try to instrument at three level 1. just before the MonitorEnter 2. after MonitorEnter 3. Before MonitorExit.
1 and 3 together works fine, but when i do 2, the execution time increase dramatically.
Even if we instrument another single SOP statement, which is intended to be executed just once, it give higher values.
Here the sample code (prime number, 10 loops):
for(int w=0;w<10;w++){
synchronized(s){
long t1 = System.currentTimeMillis();
long num = 2000;
for (long i = 1; i < num; i++) {
long p = i;
int j;
for (j = 2; j < p; j++) {
long n = p % i;
}
}
long t2 = System.currentTimeMillis();
System.out.println("Time>>>>>>>>>>>> " + (t2-t1) );
}
Here the code for instrumention (here System.currentMilliSeconds() gives the time at which instrumention happened, its no the measure of execution time, the excecution time is from obove SOP statement):
public void visitInsn(int opcode)
{
switch(opcode)
{
// Scenario 1
case 194:
visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io /PrintStream;");
visitLdcInsn("TIME Arrive: "+System.currentTimeMillis());
visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V");
break;
// scenario 3
case 195:
visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
visitLdcInsn("TIME exit : "+System.currentTimeMillis());
visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V");
break;
}
super.visitInsn(opcode);
// scenario 2
if(opcode==194)
{
visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
visitLdcInsn("TIME enter: "+System.currentTimeMillis());
visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V");
}
}
I am not able to find the reason why it is happening and how t correct it.
Thanks in advance.
The reason lies in the internals of the JVM that you were using for running the code. I assume that this was a HotSpot JVM but the answers below are equally right for most other implementations.
If you trigger the following code:
int result = 0;
for(int i = 0; i < 1000; i++) {
result += i;
}
This will be translated directly into Java byte code by the Java compiler but at run time the JVM will easily see that this code is not doing anything. Executing this code will have no effect on the outside (application) world, so why should the JVM execute it? This consideration is exactly what compiler optimization does for you.
If you however trigger the following code:
int result = 0;
for(int i = 0; i < 1000; i++) {
System.out.println(result);
}
the Java runtime cannot optimize away your code anymore. The whole loop must always run since the System.out.println(int) method is always doing something real such that your code will run slower.
Now let's look at your example. In your first example, you basically write this code:
synchronized(s) {
// do nothing useful
}
This entire code block can easily be removed by the Java run time. This means: There will be no synchronization! In the second example, you are writing this instead:
synchronized(s) {
long t1 = System.currentTimeMillis();
// do nothing useful
long t2 = System.currentTimeMillis();
System.out.println("Time>>>>>>>>>>>> " + (t2-t1));
}
This means that the effective code might be look like this:
synchronized(s) {
long t1 = System.currentTimeMillis();
long t2 = System.currentTimeMillis();
System.out.println("Time>>>>>>>>>>>> " + (t2-t1));
}
What is important here is that this optimized code will be effectively synchronized what is an important difference with respect to execution time. Basically, you are measuring the time it costs to synchronize something (and even that might be optimized away after a couple of runs if the JVM realized that the s is not locked elsewhere in your code (buzzword: temporary optimization with the possibility of deoptimization if loaded code in the future will also synchronize on s).
You should really read this:
http://www.ibm.com/developerworks/java/library/j-jtp02225/
http://www.ibm.com/developerworks/library/j-jtp12214/
Your test for example misses a warm-up, such that you are also measuring how much time the JVM will use for byte code to machine code optimization.
On a side note: Synchronizing on a String is almost always a bad idea. Your strings might be or might not be interned what means that you cannot be absolutely sure about their identity. This means, that synchronization might or might not work and you might even inflict synchronization of other parts of your code.
I have a boost multi_index_container declared as below which is indexed by hash_unique id(unsigned long) and hash_non_unique transaction id(long). Insertion and retrieval of elements is fast but when I delete elements, it is much slower. I was expecting it to be constant time as key is hashed.
e.g To erase elements from container
for 10,000 elements, it takes around 2.53927016 seconds
for 15,000 elements, it takes around 7.137100068 seconds
for 20,000 elements, it takes around 21.391720757 seconds
Is it something I am missing or is it expected behavior?
class Session
{
public:
Session() {
//increment unique id
static unsigned long counter = 0;
boost::mutex::scoped_lock guard(mx);
counter++;
m_nId = counter;
}
unsigned long GetId() {
return m_nId;
}
long GetTransactionHandle(){
return m_nTransactionHandle;
}
....
private:
unsigned long m_nId;
long m_nTransactionHandle;
boost::mutext mx;
....
};
typedef multi_index_container<
Session*,
indexed_by<
hashed_unique< mem_fun<Session,unsigned long,&Session::GetId> >,
hashed_non_unique< mem_fun<Session,unsigned long,&Session::GetTransactionHandle> >
> //end indexed_by
> SessionContainer;
typedef SessionContainer::nth_index<0>::type SessionById;
int main() {
...
SessionContainer container;
SessionById *pSessionIdView = &get<0>(container);
unsigned counter = atoi(argv[1]);
vector<Session*> vSes(counter);
//insert
for(unsigned i = 0; i < counter; i++) {
Session *pSes = new Session();
container.insert(pSes);
vSes.push_back(pSes);
}
timespec ts;
lock_settime(CLOCK_PROCESS_CPUTIME_ID, &ts);
//erase
for(unsigned i = 0; i < counter; i++) {
pSessionIdView->erase(vSes[i]->getId());
delete vSes[i];
}
lock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts);
std::cout << "Total time taken for erase:" << ts.tv_sec << "." << ts.tv_nsec << "\n";
return (EXIST_SUCCESS);
}
In your test code, what value for m_nTransactionHandledo the Session objects receive? Could it be it's the same value for all the objects? If so, erasing will take long, as performance of hashed containers is poor when there are many equal elements. Try assigning different m_nTransactionHandle values on creation to see if this speeds your test up.
When erasing an element, performance is a function of all the indices making up the container (basically, the element must be erased from every index, not only the index you're currently working with). Hashed indices are badly hurt when there are many equivalent elements, this is not the pattern they're designed to work against.
I just found that the performance for hashed_non_unique versus hashed_unique for 2nd index is the almost same except slight overhead of checking duplicate.
The bottleneck was with boost::object_pool. I don't know internal implementation but it seem it is a list where it iterate through the list to find objects. See the link for performance results and source code.
http://joshitech.blogspot.com/2010/05/boost-object-pool-destroy-performance.html