Summary

Write a program or function, which doesn't take any input, and outputs all the integer numbers, between -1000 and 1000 in ascending order, to the stdout, one per line, like this:

-1000
-999
-998
-997
...

And after that you need to print the time taken to print these numbers, or the time from the start of the program's execution in milliseconds. It can be a float, or an integer (if you print an integer, you need to round down to the nearest).

Example code

using System;
using System.Diagnostics;
class P
{
    static void Main(string[] args)
    {
        Stopwatch st = Stopwatch.StartNew();
        for (int i = -1000; i <= 1000; i++)
        {
            Console.WriteLine(i);
        }
        Console.WriteLine(st.ElapsedMilliseconds);      
    }
}

Restrictions

Standard loopholes are not allowed

Other infos

It's code golf, so the shortest submission wins.

share|improve this question
    
@GurupadMamadapur No, sorry – Horváth Dávid yesterday
    
Why? I think essentially to print those numbers every statement is involved from the start of the program right? – Gurupad Mamadapur yesterday
1  
@GurupadMamadapur Ok, you're right, I will edit the question accordingly. – Horváth Dávid yesterday
    
Can the program wait some amount of time from the start, and print that amount? – xnor yesterday
    
@xnor I think, that would change the challenge, and because there are already lots of answers to the original challenge, I would say no. – Horváth Dávid yesterday

32 Answers 32

Octave, 46 43 36 30 23 bytes

tic;(-1e3:1e3)',toc*1e3

This will print:

ans =

  -1000
   -999
   -998
   -997
   -996
   -995

If you don't like the ans =, then we have to add an additional 6 bytes for disp:

tic;disp((-1e3:1e3)'),toc*1e3

Saved a lot of bytes thanks to a few reminders from rahnema1.

Explanation:

tic;                              % Starts timer
         (-1e3:1e3)'              % A vertical vector -1000 ... 1000
    disp((-1e3:1e3)'),            % Display this vector
                      toc*1e3     % Stop the timer and output the time in milliseconds
share|improve this answer

JavaScript, 60 bytes

(c=console).time();for(i=~1e3;i++<1e3;c.log(i));c.timeEnd();

In order to get all the events logged, you should use the script from the developer console (otherwise the logs are erased after the certain amount of them).

share|improve this answer
    
i=~1e3 to save a byte :-) – ETHproductions yesterday
    
Thank you, @eth :) – nicael yesterday

MATL, 13 bytes

1e3t_y&:!DZ`*

Try it online!

       % Implicitly start timer
1e3    % Push 1000
       % STACK: 1000
t_     % Duplicate, negate
       % STACK: 1000, -1000
y      % Duplicate second-top number
       % STACK: 1000, -1000, 1000
&:     % Two-input range
       % STACK: 1000, [-1000, 999, ..., 1000]
!      % Transpose into column vector
       % STACK: 1000, [-1000; 999; ...; 1000]
D      % Display
       % STACK: 1000
Z`     % Push timer value, say t
       % STACK: 1000, t
*      % Multiply
       % STACK: 1000*t
       % Implicitly display
share|improve this answer
2  
Very nice! Smart to implement: Implicitly start timer. Was that there from day one, or is that the result of an earlier challenge? – Stewie Griffin yesterday
    
@StewieGriffin Not from day one. I added it on 13 Jul 2016, probably after having to intiallize it explicitly in a couple of challenges – Luis Mendo yesterday

CJam, 18 bytes

es2001{1e3-n}/es\-

Try it online!

How it works

es                  Push the current time (milliseconds since epoch) on the stack.
  2001{     }/      For each integer X from 0 to 2000:
       1e3-           Subtract 1000 from X.
           n          Print with a newline.
              es    Push the current time on the stack.
                \-  Swap and subtract.
share|improve this answer

Python 3.5, 80 77 73 bytes

import time
*map(print,range(-1000,1001)),
print(time.process_time()*1e3)

Previous solutions involved using timeit and time.time(), they were larger.

Sadly, time.process_time() was introduced in python 3.3.

Thanks to Dennis for saving 4 bytes!

share|improve this answer

R, 42 bytes

system.time(cat(-1e3:1e3,sep="\n"))[3]*1e3

This will print

.
.
.
998
999
1000
elapsed 
     60 

To remove elapsed, two additional bytes are necessary:

system.time(cat(-1e3:1e3,sep="\n"))[[3]]*1e3
share|improve this answer

Bash + GNU utils, 43

  • Saved 2 bytes thanks to @Dennis
  • Saved 5 bytes thanks to @zeppelin
c=date\ +%s%3N
s=`$c`
seq -1e3 1e3
$c-$s|bc

The date command gives the number of seconds since the epoch concatenated with current nanoseconds. This command is run before and after. bc takes the difference and prints.

Try it online.


I was hoping to do this for 17:

time seq -1e3 1e3

But the output of time gives more than we need:

real    0m0.004s
user    0m0.000s
sys 0m0.004s
share|improve this answer
1  
You can save two bytes by replacing 1000 with 1e3. – Dennis yesterday
    
"But the output of time gives ...." ...perhaps you should man bash. – H Walters yesterday
1  
You can probably save a few bytes, by capturing the date with ms precision directly, like this: date +%s%3N. – zeppelin yesterday

Bash (+coreutils), 41, 49, 46, 44, 42 bytes

EDITS:

  • Refactored to use Bash-builtin (time), to address @Dennis precision concerns;
  • Reduced by 3 bytes, by utilizing Bash 4+ |& for stderr redirection;
  • Saved 2 more bytes by replacing seq -1000 1000 with seq -1e3 1e3 (Thanks @Dennis !);
  • -2 bytes by removing unnecessary backslash, and using default precision (Thx @Dennis !).

Golfed

TIMEFORMAT=%R*1000;(time seq -1e3 1e3)|&bc

Try It Online !

Sidenote

Using a coreutils "time" utility, instead of the Bash-builtin, results in a 41, 35 byte solution:

\time -f "%e*1000" seq -1e3 1e3|&bc

"\" is here to make bash invoke the real command, instead of the builtin.

Unfortunately coreutils time precision is only 1/100s, which have raised concerns on if it is a valid solution.

share|improve this answer

R, 66 bytes

x=proc.time();for(i in -1e3:1e3)cat(i,"\n");(proc.time()-x)[3]*1e3

Probably not the shortest but it works.

share|improve this answer

Mathematica, 51 bytes

p[1*^3#]&@@AbsoluteTiming@Array[p=Print,2001,-1*^3]

Explanation

Array[p=Print,2001,-1*^3]

Store the Print function in p. Print 2001 numbers, starting at -1000, incrementing by 1.

AbsoluteTiming@ ...

Find the total time elapsed in seconds.

p[1*^3#]&@@ ...

Multiply that by 1000 (seconds -> miliseconds) and p (Print) it.

share|improve this answer
    
Argh, you beat me by 3 minutes! :) Are you sure Timing doesn't satisfy the (slightly vague) problem description as well as AbsoluteTiming? – Greg Martin yesterday
2  
@GregMartin Timing outputs the CPU time and does not include the time taken by the front end. That is. the time taken to increment the counter in Array is counted, but the time taken to display those numbers on screen is not counted. This effect can be seen in this simple example: Timing@Print@3 gives 0 seconds, but AbsoluteTiming@Print@3 does not. – JungHwan Min yesterday

PHP, 110 70 bytes

still a little long; but saved 38 with @AlexHowansky´s hint, and two more with 1e3 and ~1e3.

for($t=($m=microtime)($i=~1e3);$i++<1e3;)echo"$i
";echo($m(1)-$t)*1e3;

prints float. Run with -r.

share|improve this answer
2  
You can pass microtime() a truthy value and it will return a float directly, you don't have to add the strings. – Alex Howansky yesterday
    
-30% with that hint. I wish I could do ten upvotes on your comment. :D – Titus yesterday
    
It's sad how PHP doesn't have something that returns the time in milliseconds. Like Javascript has. I can't suggest improvements. It's as small as it can get. Well done! – Ismael Miguel 47 mins ago
    
@IsmaelMiguel I think JavaScript doesn´t have microseconds. :) – Titus 22 mins ago
    
@Titus What I meant is that Javascript's dates are all handled in milliseconds, while PHP only had seconds or microseconds. – Ismael Miguel 6 mins ago

JavaScript (ES6), 63 bytes

for(t=new(d=Date),c=console.log,i=~1e3;i<1e3;c(++i));c(new d-t)

share|improve this answer
    
Nice. You can save three bytes by removing the space in new (d=Date) and starting at -1000: for(t=new(d=Date),c=console.log,i=~1e3;i<1e3;c(++i));c(new d-t) – ETHproductions yesterday
    
@ETHproductions thanks :) the ~1e3 is a great touch. – George Reith yesterday
1  
In the snippet output is from only 952 to 1000 why is that? – Gurupad Mamadapur yesterday
    
@GurupadMamadapur The snippet output is limited to 50 lines. (Or more precisely: the 50 last lines.) – Arnauld yesterday
    
@Arnauld Oh okay. – Gurupad Mamadapur yesterday

8th, 61 bytes

( ( . cr ) -1000 1000 loop ) d:msec >r w:exec d:msec r> n:- .

This will print all the integer numbers between -1000 and 1000 in ascending order and the time taken (in millisecons) to print these numbers

-1000
-999
-998
-997
...
997
998
999
1000
4
share|improve this answer

Perl 6, 45 bytes

.put for -($_=1e3)..$_;put (now -INIT now)*$_

Try it

Expanded:

# print the values

.put             # print with trailing newline ( method call on 「$_」 )

for              # for each of the following
                 # ( temporarily sets 「$_」 to the value )

-(
  $_ = 1e3       # store 「Num(1000)」 in 「$_」
)
..               # inclusive Range object
$_;

# print the time elapsed

put              # print with trailing newline

(now - INIT now) # Duration object that numifies to elapsed seconds
* $_             # times 1000 to bring it to milliseconds

# The 「INIT」 phaser runs code (the second 「now」) immediately
# as the program starts.

# There is no otherwise unrelated set-up in this code so this is a
# reliable indicator of the amount of time it takes to print the values.
share|improve this answer

J, 22 bytes

1e3*timex'echo,.i:1e3'

Try it online!

timex is a builtin that executes the string and returns the time it took to evaluate it in seconds. The string forms the range [-1000, 1000] using i:, then columinizes it using ,., and prints it using the builtin echo.

share|improve this answer

Powershell, 42 Bytes

$1=date;-1e3..1e3;((date)-$1).Milliseconds

Save time before as $1, print to stdout automatically, then get the time between the beginning and end of execution.

Measure-Command is another option I considered, but it stops printing to stdout, and doesn't have a shorter default alias.

share|improve this answer

Pyth, 18 15 14 bytes

j}_J^T3J;*.d1J

Try it here!

Explanation

This is similar to my python answer.

    J^T3           Set J to 1000
  }_    J         List ranging from -1000 to 1000
j                 Join the list with new lines and implicitly print it
         ;*.d1J   Print time since execution of the program in milliseconds

Edits:

share|improve this answer
    
I tried this, 14 bytes, not sure if it works right. You need to add a newline at the start of the program. pyth.herokuapp.com/?code=%0AM%7D_J%5ET3J%2a.d1J&debug=0 – busukxuan yesterday

Noodel, 17 13 bytes

13 bytes

Tried a slightly different approach and saved 4 bytes.

ƇQjȥḶGQɱ⁻Ñ€Ƈ⁻

Try it:)

How it works

Ƈ             # Pushes on the amount of milliseconds passed since 01/01/1970.

 Qjȥ          # Pushes 2001 onto the stack.
 Qj           # Pushes on the string "Qj"
   ȥ          # Converts the string into a number as base 98.

    ḶGQɱ⁻Ñ€   # Loops 2001 times printing -1000 to 1000.
    Ḷ         # Consumes the 2001 and loops the following code 2001 times.
     GQ       # Pushes on the string "GQ"
       ɱ      # Pushes on the current counter of the loop (i)
        ⁻     # Subtracts (i - "GQ") since i is a number, the "GQ" is converted to a number which will fail.
              # So, Noodel will treat the string as a base 98 number producing (i - 1000). 
         Ñ    # Consume what is on the top of the stack pushing it to the screen followed by a new line.
          €   # The end of the loop.

           Ƈ⁻ # Calculates the duration of execution.
           Ƈ  # Pushes on the amount of milliseconds passed since 01/01/1970.
            ⁻ # Pushes on (end - start)

17 bytes

ƇGQȥḋɲṡ×2Ḷñ⁺1€ÑƇ⁻

Try it:)

How it works

Ƈ                 # Pushes on the amount of milliseconds passed since 01/01/1970.

 GQȥḋɲṡ×2         # Used to create the range of numbers to be printed.
 GQ               # Pushes on the string "GQ".
   ȥ              # Converts the string into number as if it were a base 98 number. (which is 1000)
    ḋ             # Duplicates the number and pushes it onto the stack. 
     ɲ            # Since the item on top is already a number, makes the number negative (random thing I threw in at the very beginning when made the langauge and totally forgot it was there)
      ṡ           # Swaps the first two items on the stack placing 1000 on top.
       ×2         # Doubles 1000 producing... 2000

         Ḷñ⁺1€Ñ   # Prints all of the numbers from -1000 to 1000.
         Ḷ        # Consumes the 2000 to loop the following code that many times (now -1000 is on the top).
          ñ       # Prints the value on top of the stack followed by a new line.
           ⁺1     # Increment the value on top of the stack by 1.
             €    # End of the loop.
              Ñ   # Since 1000 is still not printed, this consumes 1000 and prints it followed by a new line.

               Ƈ⁻ # Calculates the number of milliseconds to execute program.
               Ƈ  # Pushes on the amount of milliseconds passed since 01/01/1970.
                ⁻ # Pushes on (end - start) in milliseconds.
                  # At the end, the top of the stack is pushed to the screen.

The snippet uses the values -4 to 4 in order to not take so long to complete.

<div id="noodel" code="ƇFȥḶAɱ⁻Ñ€Ƈ⁻" input="" cols="10" rows="10"></div>

<script src="https://tkellehe.github.io/noodel/noodel-latest.js"></script>
<script src="https://tkellehe.github.io/noodel/ppcg.min.js"></script>

share|improve this answer
    
Did you create this language after or before the challenge? – Easterly Irk 15 hours ago
    
@EasterlyIrk, before:) – tkellehe 14 hours ago

TI-Basic, 22 bytes

startTmr
For(A,-ᴇ3,ᴇ3
Disp A
End
startTmr-Ans
  • Many commands are represented by 1 or 2-byte tokens.

  • Tested on an emulated TI-84 CSE.

share|improve this answer

Matlab, 16 23 Bytes

tic;(-1e3:1e3)'
toc*1e3

Edit: I realised I was violating several of this challenge's rules. That'll teach me to skim read the challenge late at night. I also now realise that the corrected answer is almost identical to the Octave solution, but such is life.

Prints each element in the created linear space array -1000:1000 (the lack of ; prints to console).

tic/toc records the time and toc prints the time to the console with or without the ; . 1e3 is needed to print in milliseconds.

share|improve this answer
    
Quite right, a correct solution has been edited. – Owen Morgan 22 hours ago

Groovy, 75 73 bytes

t=System.&nanoTime
s=t()
(-1000..1e3).each{println it}
print((t()-s)/1e6)

Thanks to jaxad0127 for saving 2 bytes!

Try it here !

share|improve this answer
1  
nanoTime with a divide by 1e6 is shorter than currentTimeMillis. It also gives fractional time. – jaxad0127 21 hours ago

QBIC, 34 bytes

d=timer[-z^3,z^3|?a]?z^3*(timer-d)

Uses the QBasic TIMER function, which returns seconds in decimal notation. Making it look pretty adds some bytes.

Explanation

d=timer     Set 'd' to the current # seconds since midnight
[-z^3,z^3|  FOR -1000 to 1000  --  Note that 'z' = 10 in QBIC, and z^3 saves a byte over 1000
?a          Display the iterator
]           Close the FOR loop
    timer-d Take the current time minus the time at the start of the program -- 0.156201
?z^3*()     Multiply by a thousand and display it   156.201
share|improve this answer

Racket Scheme, 72 bytes

(time(map(lambda(x)(display(exact-floor x))(newline))(range -1e3 1001)))
share|improve this answer

C++ - 261

Just for a laugh I thought I'd post a C++ answer.

#include <iostream>
#include <chrono>
using namespace std::chrono; using c=std::chrono::system_clock; void p(){c::time_point n=c::now();for(int i=-1001;++i<1001;)std::cout<<i<<"\n";std::cout<<(duration_cast<milliseconds>(system_clock::now()-n)).count()<<"\n";}

I'll leave it as an exercise to determine what it is doing and how to call it - shouldn't be too difficult.

share|improve this answer

Scala, 77 bytes

def t=System.nanoTime
val s=t
Range(-1000,1001)map println
println((t-s)/1e6)
share|improve this answer

ForceLang, 124

set t timer.new()
set i -1000
label 1
io.writeln set i i+1
if i=1000
 io.write math.floor 0.001.mult t.poll()
 exit()
goto 1

Note: You should supress stderr when running this. I believe the consensus on meta is that this does not incur a byte count penalty.

share|improve this answer

SimpleTemplate, 92 bytes

What really killed me was the need to record the time.

{@callmicrotime intoX 1}{@for_ from-1000to1000}{@echol_}{@/}{@phpecho microtime(1)-$DATA[X]}

Since there's no math (yet), this makes things pretty hard, forcing me to write PHP directly.

Ungolfed:

{@call microtime into start_time true}
{@for i from -1000 to 1000 step 1}
    {@echol i}{@// echoes a newline after}
{@/}
{@php echo microtime(true) - $DATA["start_time"];}

Disclaimer:

I've ran this with the commit e118ae72c535b1fdbe1b80c847f52aa161854fda, from 2017-01-13.

The latest commit was to fix something that is un-related to the code in here.

share|improve this answer

C 134 133 bytes

Thanks to @Thomas Padron-McCarthy for saving 1 byte.

f(){clock_t s,e;s=clock();for(int i=-1000;i<1001;i++)printf("%d\n",i);e=clock();printf("%lf",((double)((e-s))/(CLOCKS_PER_SEC))*1e3);}

Ungolfed version :

void f()
{   
  clock_t s,e;

  s=clock();

  for(int i=-1000;i<1001;i++)
    printf("%d\n",i);   

  e=clock();
  printf("%f",((double)((e-s))/(CLOCKS_PER_SEC))*1e3);

 }
share|improve this answer
    
You can save one character by changing "%lf" to "%f". – Thomas Padron-McCarthy 4 hours ago

C# - 123

This isn't going to win anything but hey, here it goes :)

()=>{var t=DateTime.Now;var s="";for(int i=-1000;i<1001;i++)s+=i+"\n";Console.WriteLine(s+(DateTime.Now-t).Milliseconds);};

Run like this:

Action y = ()=>{var t=DateTime.Now;var s="";for(int i=-1000;i<1001;i++)s+=i+"\n";Console.WriteLine(s+(DateTime.Now-t).Milliseconds);};
y();
share|improve this answer

Lua, 47 Characters

for i=-1e3,1e3 do print(i)end print(os.clock())

It's nice and simple, a basic printing for loop from -1e3 to 1e3, then just print the os.clock, which is conveniently the ms since program execution.

share|improve this answer

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.