Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Task

Using any type of parallelisation, wait multiple periods, for a total sleep time of at least a minute (but less than a minute and a half).

The program/function must terminate within 10 seconds and return (by any means and in any format) two values: the total elapsed time, and the total executed sleep time. Both time values have to have a precision of at least 0.1 second.

This is similar to the concept of man-hours: a job that takes 60 hours can be completed in only 6 hours if 10 workers are splitting the job. Here we can have 60 seconds of sleep time e.g. in 10 parallel threads, thus requiring only 6 seconds for the whole job to be completed.

Example

The program MyProgram creates 14 threads, each thread sleeps for 5 seconds:

MyProgram[5.016,70.105]

The execution time is greater than 5 seconds, and the total sleep time is greater than 70 seconds because of overhead.

share|improve this question
2  
I've read the question several times and I don't get it. Can you clarify a bit? Why "10 seconds" and a delay of "70 seconds"? How are all those times related? – Luis Mendo yesterday
3  
How many threads can we assume will be executed in parallel? – miles yesterday
3  
What precision is required for the time in output? – edc65 yesterday
3  
I wonder if this will cause all the golfing language authors to engage in a mad dash to add multi-threading to their creations... – Adám 19 hours ago
3  
4 close votes. Can someone explain what isn't clear here? – Adám 15 hours ago

20 Answers 20

Python 2, 179 bytes

from threading import*
from time import*
m=time
s=m()
t=[0]
r=[]
def f():n=m();sleep(9);t[0]+=m()-n
exec"r+=[Thread(None,f)];r[-1].start();"*8
for d in r:d.join()
print m()-s,t[0]

This requires an OS with time precision greater than 1 second to work properly (in other words, any modern OS). 8 threads are created which sleep for 9 seconds each, resulting in a realtime runtime of ~9 seconds, and a parallel runtime of ~72 seconds.

Though the official documentation says that the Thread constructor should be called with keyword arguments, I throw caution to the wind and use positional arguments anyway. The first argument (group) must be None, and the second argument is the target function.

t must be an object type (like a list), and not a simple type (like an int), or else the t in the function will be a local and not a reference to the global. Furthermore, assignment can't be used, or else a local variable will be created. Instead, element access is used to force the reference to be a reference to the global.

Try it online

Thanks to DenkerAffe for -5 bytes with the exec trick.

Thanks to kundor for -7 bytes by pointing out that the thread argument is unnecessary.

share|improve this answer
    
You can save two bytes by removing the argument to f(), and the last two arguments to Thread (thus removing 7 characters) and using t.append(m()-n) to avoid assigning a local variable t (using 5 more characters than +=.) – kundor 18 hours ago
    
And you can save five more by keeping the sum instead of a list of times: initialize t with t=[0], replace the append by t[0]+=m()-n, and replace sum(t) by t[0]. – kundor 17 hours ago
    
Thread names can be omitted. – ppperry 17 hours ago
    
@ppperry: not if you need to use the subsequent positional arguments (but as I mentioned in previous comments, you can actually elide those.) – kundor 14 hours ago

Go - 189 bytes

Thanks @cat!

package main
import(."fmt";."time");var m,t=60001,make(chan int,m);func main(){s:=Now();for i:=0;i<m;i++{go func(){Sleep(Millisecond);t<-0}()};c:=0;for i:=0;i<m;i++{c++};Print(Since(s),c)}

Outputs (ms): 160.9939ms,60001 (160ms to wait 60.001 seconds)

share|improve this answer
1  
Hello, and welcome to PPCG! This comment, @Rob In some languages the obvious solution is already (close to) the shortest. Besides, one way to view code-golf challenges is finding the shortest solution in EACH language. Otherwise Jelly will win most of the time... So: go ahead., does not mean that you should not try to golf your answer, but that it is OK if it does not win. Can you please add a golfed solution? – NoOneIsHere 18 hours ago
    
I'm sorry, I just read your edit. For golfed, you could maybe remove newlines and spaces, or change tot to something like q. – NoOneIsHere 17 hours ago
    
@NoOneIsHere, thanks for that, I'd overlooked that variable completely! Also banged together m and t. – Rob 17 hours ago
    
codebeautify.org/javaviewer -- click minify – cat 17 hours ago
    

Bash 196 117 114 93 bytes

Updated to support better time precision by integrating suggestions from @manatwork and @Digital Trauma as well as a few other space optimizations:

d()(date +$1%s.%N;)
b=`d`
for i in {1..8};{ (d -;sleep 8;d +)>>j&}
wait
bc<<<`d`-$b
bc<<<`<j`

Note that this assumes the j file is absent at the beginning.

share|improve this answer
1  
function ss(), b=`date +%s`b=$SECONDS, expr $t + $i$[t+i], `cat j`$(<j) and generally see Tips for golfing in Bash about how to reduce it to this: pastebin.com/DDqUaDug – manatwork yesterday
    
To reduce it more, better write directly a formula to the file j. I mean instead of 5↵5↵5↵… write +5+5+5… – then load it all directly into arithmetic evaluation and spare the second loop: pastebin.com/LB0BjDMZ – manatwork yesterday
    
As minimum precision was specified later, forget the b=`date +%s`b=$SECONDS suggestion. – manatwork yesterday
1  
As bash does only integer arithmetic, the entire solution needs to be rewritten to use an external tool for calculation. Typically bc: pastebin.com/eYFEVUuz – manatwork 23 hours ago
1  
@JuliePelletier Ok, I'll post it as my own answer. Still, I think you can still apply some of the golfing techniques to your answer without significantly changing the approach: pastebin.com/ssYzVs1n (93 bytes) – Digital Trauma 16 hours ago

Bash + GNU utilities, 85

\time -f%e bash -c 'for i in {1..8};{ \time -aoj -f%e sleep 8&};wait'
paste -sd+ j|bc

Forces the use of the time executable instead of the shell builtin by prefixing with a \.

Appends to a file j, which must be empty or non-existent at the start.

share|improve this answer

JavaScript (ES6), 148 bytes

with(performance)Promise.all([...Array(9)].map(_=>new Promise(r=>setTimeout(_=>r(t+=now()),7e3,t-=now())),t=0,n=now())).then(_=>alert([now()-n,t]));

Promises to wait 9 times for 7 seconds for a total of 63 seconds (actually 63.43 when I try), but only actually takes 7.05 seconds of real time when I try.

share|improve this answer
    
+1 for promises. – Cᴏɴᴏʀ O'Bʀɪᴇɴ 12 hours ago

Javascript (ES6), 212 203 145 bytes

This code creates 10 images with a time interval of exactly 6 seconds each, upon loading.

The execution time goes a tiny bit above it (due to overhead).

This code overwrites everything in the document!

P=performance,M=P.now(T=Y=0),document.body.innerHTML='<img src=# onerror=setTimeout(`T+=P.now()-M,--i||alert([P.now()-M,T])`,6e3) >'.repeat(i=10)

This assumes that you use a single-byte encoding for the backticks, which is required for the Javascript engine to do not trip.


Alternativelly, if you don't want to spend 6 seconds waiting, here's a 1-byte-longer solution that finishes in less than a second:

P=performance,M=P.now(T=Y=0),document.body.innerHTML='<img src=# onerror=setTimeout(`T+=P.now()-M,--i||alert([P.now()-M,T])`,600) >'.repeat(i=100)

The difference is that this code waits 600ms across 100 images. This will give a massive ammount of overhead.


Old version (203 bytes):

This code creates 10 iframes with a time interval of exactly 6 seconds each, instead of creating 10 images.

for(P=performance,M=P.now(T=Y=i=0),D=document,X=_=>{T+=_,--i||alert([P.now()-M,T])};i<10;i++)I=D.createElement`iframe`,I.src='javascript:setTimeout(_=>top.X(performance.now()),6e3)',D.body.appendChild(I)


Original version (212 bytes):

P=performance,M=P.now(T=Y=0),D=document,X=_=>{T+=_,Y++>8&&alert([P.now()-M,T])},[...''+1e9].map(_=>{I=D.createElement`iframe`,I.src='javascript:setTimeout(_=>top.X(performance.now()),6e3)',D.body.appendChild(I)})

share|improve this answer
1  
+1 Very nice and different approach. What would happen in a single-threaded browser? – Adám 15 hours ago
    
@Adám No change in behaviour. There would still be a delay of around 6 seconds. Firefox (a single-threaded browser) sometimes will output funny stuff like an execution time of 59999.<something>. – Ismael Miguel 15 hours ago

PowerShell v4, 144 bytes

$d=date;gjb|rjb
1..20|%{sajb{$x=date;sleep 3;((date)-$x).Ticks/1e7}>$null}
while(gjb -s "Running"){}(gjb|rcjb)-join'+'|iex
((date)-$d).Ticks/1e7

Sets $d equal to Get-Date, and clears out any existing job histories with Get-Job | Remove-Job. We then loop 1..20|%{...} and each iteration execute Start-Job passing it the script block {$x=date;sleep 3;((date)-$x).ticks/1e7} for the job (meaning each job will execute that script block). We pipe that output to >$null in order to suppress the feedback (i.e., job name, status, etc.) that gets returned.

The script block sets $x to Get-Date, then Start-Sleep for 3 seconds, then takes a new Get-Date reading, subtracts $x, gets the .Ticks, and divides by 1e7 to get the seconds (with precision).

Back in the main thread, so long as any job is still -Status "Running", we spin inside an empty while loop. Once that's done, we Get-Job to pull up objects for all the existing jobs, pipe those to Receive-Job which will pull up the equivalent of STDOUT (i.e., what they output), -join the results together with +, and pipe it to iex (Invoke-Expression and similar to eval). This will output the resultant sleep time plus overhead.

The final line is similar, in that it gets a new date, subtracts the original date stamp $d, gets the .Ticks, and divides by 1e7 to output the total execution time.


NB

OK, so this is a little bendy of the rules. Apparently on first execution, PowerShell needs to load a bunch of .NET assemblies from disk for the various thread operations as they're not loaded with the default shell profile. Subsequent executions, because the assemblies are already in memory, work fine. If you leave the shell window idle long enough, you'll get PowerShell's built-in garbage collection to come along and unload all those assemblies, causing the next execution to take a long time as it re-loads them. I'm not sure of a way around this.

You can see this in the execution times in the below runs. I started a fresh shell, navigated to my golfing directory, and executed the script. The first run was horrendous, but the second (executed immediately) worked fine. I then left the shell idle for a few minutes to let garbage collection come by, and then that run is again lengthy, but subsequent runs again work fine.

Example runs

Windows PowerShell
Copyright (C) 2014 Microsoft Corporation. All rights reserved.

PS H:\> c:

PS C:\> cd C:\Tools\Scripts\golfing

PS C:\Tools\Scripts\golfing> .\wait-a-minute.ps1
63.232359
67.8403415

PS C:\Tools\Scripts\golfing> .\wait-a-minute.ps1
61.0809705
8.8991164

PS C:\Tools\Scripts\golfing> .\wait-a-minute.ps1
62.5791712
67.3228933

PS C:\Tools\Scripts\golfing> .\wait-a-minute.ps1
61.1303589
8.5939405

PS C:\Tools\Scripts\golfing> .\wait-a-minute.ps1
61.3210352
8.6386886

PS C:\Tools\Scripts\golfing>
share|improve this answer
1  
I'll say that's fine. :-) – Adám 18 hours ago

Ruby, 92

n=->{Time.now}
t=n[]
a=0
(0..9).map{Thread.new{b=n[];sleep 6;a+=n[]-b}}.map &:join
p n[]-t,a
share|improve this answer

JavaScript (ES6, using WebWorkers), 233 215 bytes

c=s=0;d=new Date();for(i=14;i-->0;)(new Worker(URL.createObjectURL(new Blob(['a=new Date();setTimeout(()=>postMessage(new Date()-a),5e3)'])))).onmessage=m=>{s+=m.data;if(++c>13)console.log((new Date()-d)/1e3,s/1e3)}

UPD: replaced the way a worker is executed from a string with a more compact and cross-browser one, in the aspect of cross-origin policies. Won't work in Safari, if it still have webkitURL object instead of URL, and in IE.

share|improve this answer
    
I'm getting an error when I run this: { "message": "Uncaught SecurityError: Failed to construct 'Worker': Script at 'data:application/javascript,a%3Dnew%20Date()%3BsetTimeout(()%3D%3EpostMessage(n‌​ew%20Date()-a)%2C5e3)' cannot be accessed from origin 'null'.", "filename": "http://stacksnippets.net/js", "lineno": 13, "colno": 45 } – Dr Green Eggs and Iron Man 13 hours ago

Dyalog APL, 65 27 23 bytes

This is a function that ignores its argument and returns a two-element vector, the first element being the amount of time spent on the main thread, and the second being the total amount of time spent on all threads, in seconds.

{(⌈/,+/)⎕TSYNC⎕DL&¨9/7}

I.e.:

      {(⌈/,+/)⎕TSYNC⎕DL&¨9/7}⍬
7.022 63.162

Explanation:

  • ⎕DL&¨9/7: spin off 9 threads, each of which waits for 7 seconds. ⎕DL returns the actual amount of time spent waiting, in seconds, which will be the same as its argument give or take a few milliseconds.
  • ⎕TSYNC: wait for all threads to complete, and get the result for each thread.
  • (⌈/,+/): return the longest execution time of one single thread (during the execution of which all other threads finished, so this is the actual runtime), followed by the sum of the execution time of all threads.
share|improve this answer
    
This won't work if executed at 23:59:57. However, you're on the right track... While you are already the shortest, can you golf away another 40 bytes? – Adám 11 hours ago
1  
@Adám: no, but I can golf away 38 bytes. It's quite obvious, I don't know why I didn't think of this the first time around. – marinus 11 hours ago
    
There you go. Only another 6 bytes until you get a checkmark. The three things you have to do are pretty obvious too, saving 1, 2, and 3 bytes respectively. – Adám 11 hours ago
    
Very nice, you found number 1 and number 3. Number 2 isn't really golfing, as much as an implementation alternative... – Adám 10 hours ago

Javascript (ES6), 105 bytes

((t,c,d)=>{i=t();while(c--)setTimeout((c,s)=>{d+=t()-s;if(!c)alert([t()-i,d])},8e3,c,t())})(Date.now,8,0)

Updated version: 106 bytes Borrowed from @Ismael Miguel as he had the great idea to lower sleep time and raise intervals.

((t,c,d)=>{i=t();while(c--)setTimeout((c,s)=>{d+=t()-s;if(!c)alert([t()-i,d])},610,c,t())})(Date.now,99,0)

Javascript Ungolfed, 167 bytes

(function(t, c, d){
	i = t();
	while(c--){
		setTimeout(function(c, s){
			d += t() - s;
			if (!c) alert([t() - i, d])
		}, 8e3, c, t())
	}
})(Date.now, 8, 0)

share|improve this answer

Java, 358 343 337 316 313 bytes

import static java.lang.System.*;class t extends Thread{public void run(){long s=nanoTime();try{sleep(999);}catch(Exception e){}t+=nanoTime()-s;}static long t,i,x;public static void main(String[]a)throws Exception{x=nanoTime();for(;++i<99;)new t().start();sleep(9000);out.println((nanoTime()-x)/1e9+" "+t/1e9);}}

and ungolfed

import static java.lang.System.*;

class t extends Thread {
    public void run() {
        long s = nanoTime();
        try {
            sleep(999);
        } catch (Exception e) {
        }
        t += nanoTime() - s;
    }

    static long t,i,x;

    public static void main(String[] a) throws Exception {
        x = nanoTime();
        for (; ++i < 99;)
            new t().start();
        sleep(9000);
        out.println((nanoTime() - x) / 1e9 + " " + t / 1e9);
    }
}

please don't try it at home, as this solution is not thread safe.

Edit:

I took @A Boschman's and @Adám's suggestions, and now my program require less than 10 seconds to run, and it's shorter by 15 bytes.

share|improve this answer
2  
You're inside a child of the Thread class, can't you omit the Thread. at the static sleep() method calls? Also, won't this program terminate in slightly over 10 seconds, disqualifying it? – A Boschman 20 hours ago
    
@ABoschman thanks for suggestion, and its fixed by now, it doesn't run more than 10 sec anymore – user902383 20 hours ago
    
@user902383 If I recall correctly, you can omit the public keyword as it is implicit. Also, int may not be required when defining a function (try it, and tell me if that works) – Katenkyo 20 hours ago
1  
Also, don't forget we have a great userbase of tips for golfing in java :) – Katenkyo 20 hours ago
1  
You can remove the long before the s and add ,s to the static long t,i,s; to save a few bytes. – Kevin Cruijssen 2 hours ago

Rust, 257, 247 bytes

I use the same times as Mego's Python answer.

Really the only slightly clever bit is using i-i to get a Duration of 0 seconds.

fn main(){let n=std::time::Instant::now;let i=n();let h:Vec<_>=(0..8).map(|_|std::thread::spawn(move||{let i=n();std::thread::sleep_ms(9000);i.elapsed()})).collect();let mut t=i-i;for x in h{t+=x.join().unwrap();}print!("{:?}{:?}",t,i.elapsed());}

Prints:

Duration { secs: 71, nanos: 995877193 }Duration { secs: 9, nanos: 774491 }

Ungolfed:

fn main(){
    let n = std::time::Instant::now;
    let i = n();
    let h :Vec<_> =
        (0..8).map(|_|
            std::thread::spawn(
                move||{
                    let i = n();
                    std::thread::sleep_ms(9000);
                    i.elapsed()
                }
            )
        ).collect();
    let mut t=i-i;
    for x in h{
        t+=x.join().unwrap();
    }
    print!("{:?}{:?}",t,i.elapsed());
}

Edit: good old for loop is a bit shorter

share|improve this answer
    
+1 Any output format is good. – Adám 19 hours ago

Ruby (with parallel gem), 123 bytes

require 'parallel'
t=Time.now
q=0
Parallel.each(1..10,:in_threads=>10){z=Time.now;sleep 6;q+=Time.now-z}
puts Time.now-t,q
share|improve this answer

Groovy, 158 characters

d={System.currentTimeMillis()}
s=d(j=[])
13.times{Thread.start{b=d()
sleep 5000
synchronized(j){j<<d()-b}}}addShutdownHook{print([(d()-s)/1000,j.sum()/1000])}

Sampler run:

bash-4.3$ groovy wait1minute.groovy 
[5.082, 65.164]
share|improve this answer

Mathematica, 109 bytes

a=AbsoluteTiming;LaunchKernels@7;Plus@@@a@ParallelTable[#&@@a@Pause@9,{7},Method->"EvaluationsPerKernel"->1]&

Anonymous function. Requires a license with 7+ sub-kernels to run. Takes 9 seconds realtime and 63 seconds kernel-time, not accounting for overhead. Make sure to only run the preceding statements once (so it doesn't try to re-launch kernels). Testing:

In[1]:= a=AbsoluteTiming;LaunchKernels@7;func=Plus@@@a@ParallelTable[#&@@a@Pause
@9,{7},Method->"EvaluationsPerKernel"->1]&;

In[2]:= func[]

Out[2]= {9.01498, 63.0068}

In[3]:= func[]

Out[3]= {9.01167, 63.0047}

In[4]:= func[]

Out[4]= {9.00587, 63.0051}
share|improve this answer
    
Leave it to Wolfram to put license restrictions on forking a child process. – Mario Carneiro 4 hours ago

Javascript (ES6), 108 bytes

I'm making a new answer since this uses a slightly different aproach.

It generates a massive amount of setTimeouts, which are almost all executed with 4ms between them.

Each interval is of 610 milliseconds, over a total of 99 intervals.

P=performance,M=P.now(T=Y=0),eval('setTimeout("T+=P.now()-M,--i||alert([P.now()-M,T])",610);'.repeat(i=99))

It usually runs within 610ms, for a total execution time of around 60.5 seconds.

This was tested on Google Chrome version 51.0.2704.84 m, on windows 8.1 x64.

share|improve this answer

C, 128 bytes (spins CPU)

This solution spins the CPU instead of sleeping, and counts time using the times POSIX function (which measures CPU time consumed by the parent process and in all waited-for children).

It forks off 7 processes which spin for 9 seconds apiece, and prints out the final times in C clocks (on most systems, 100 clock ticks = 1 second).

t;v[4];main(){t=time(0);fork(fork(fork()));while(time(0)<=t+9);wait(0);wait(0);wait(0)>0&&(times(v),printf("%d,%d",v[0],v[2]));}

Sample output:

906,6347

meaning 9.06 seconds real time and 63.47 seconds total CPU time.

For best results, compile with -std=c90 -m32 (force 32-bit code on a 64-bit machine).

share|improve this answer

C (with pthreads), 339 336 335 bytes

#include<stdio.h>
#include<sys/time.h>
#include<pthread.h>
#define d double
d s=0;int i;pthread_t p[14];d t(){struct timeval a;gettimeofday(&a,NULL);return a.tv_sec+a.tv_usec/1e6;}
h(){d b=t();sleep(5);s+=t()-b;}
main(){d g=t();for(i=14;i-->0;)pthread_create(&p[i],0,&h,0);for(i=14;i-->0;)pthread_join(p[i],0);printf("%f %f",t()-g,s);}
share|improve this answer

C99, 59 Bytes

int main(){for(int i=0;i<10;i++)system("time sleep 10 &");}

To compile on Linux:
gcc codegolf.c --std=c99 -o codegolf

Output (time values bolded):

0inputs+0outputs (0major+78minor)pagefaults 0swaps 0.00user 0.00system 0:10.00 elapsed 0%CPU (0avgtext+0avgdata 1844maxresident)k 0inputs+0outputs (0major+79minor)pagefaults 0swaps 0.00user 0.00system 0:10.00 elapsed 0%CPU (0avgtext+0avgdata 1840maxresident)k 0inputs+0outputs (0major+79minor)pagefaults 0swaps 0.00user 0.00system 0:10.00 elapsed 0%CPU (0avgtext+0avgdata 1828maxresident)k 0inputs+0outputs (0major+78minor)pagefaults 0swaps 0.00user 0.00system 0:10.00 elapsed 0%CPU (0avgtext+0avgdata 1848maxresident)k 0inputs+0outputs (0major+79minor)pagefaults 0swaps 0.00user 0.00system 0:10.00 elapsed 0%CPU (0avgtext+0avgdata 1840maxresident)k 0inputs+0outputs (0major+79minor)pagefaults 0swaps 0.00user 0.00system 0:10.00 elapsed 0%CPU (0avgtext+0avgdata 1812maxresident)k 0inputs+0outputs (0major+78minor)pagefaults 0swaps 0.00user 0.00system 0:10.00 elapsed 0%CPU (0avgtext+0avgdata 1848maxresident)k 0inputs+0outputs (0major+79minor)pagefaults 0swaps 0.00user 0.00system 0:10.00 elapsed 0%CPU (0avgtext+0avgdata 1920maxresident)k 0inputs+0outputs (0major+80minor)pagefaults 0swaps 0.00user 0.00system 0:10.00 elapsed 0%CPU (0avgtext+0avgdata 1936maxresident)k 0inputs+0outputs (0major+80minor)pagefaults 0swaps

Notes:

  • The output is a bit mangled, but, nothing in the rules says it has to be nicely formatted :).
  • This must be run on a Unix-like system (ie. won't work on Windows)
  • The actual C program terminates almost instantly, but, the subprocesses it spawns (which many would argue are part of the same program) still run for the allotted amount of time.
share|improve this answer
    
@Adám Done (extra characters) – john01dav 21 hours ago
1  
This does not display the required output as specified in the question. The difference is not a matter of "formatting". – dan1111 21 hours ago
    
@dan1111 True, but, that doesn't make it useless. If the op wants to disqualify it, then I guess that makes sense. – john01dav 21 hours ago
    
Not disqualify, you just have to fix it so it outputs the the total of all those 0:10.00s and so that it measures its own runtime too. – Adám 21 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.