Created
November 4, 2011 09:00
-
-
Save hpcx82/1338959 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.ComponentModel; | |
using System.Diagnostics; | |
namespace timeit | |
{ | |
class Program | |
{ | |
static int Main(string[] args) | |
{ | |
if (args.Length == 0) | |
{ | |
Console.WriteLine("Usage: timeit <program> [args...]"); | |
return -1; | |
} | |
Stopwatch timer = new Stopwatch(); | |
timer.Start(); | |
// Run the actual program | |
int exitCode = 0; | |
try | |
{ | |
exitCode = RunProgram(args); | |
} | |
catch (Win32Exception) | |
{ | |
Console.WriteLine("\"" + args[0] + "\"" + " is not a valid program!"); | |
return -1; | |
} | |
catch (Exception e) | |
{ | |
Console.WriteLine(e.Message); | |
return -1; | |
} | |
timer.Stop(); | |
OutputTime(timer); | |
return exitCode; | |
} | |
static void OutputTime(Stopwatch timer) | |
{ | |
TimeSpan ts = timer.Elapsed; | |
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", | |
ts.Hours, ts.Minutes, ts.Seconds, | |
ts.Milliseconds / 10); | |
Console.WriteLine("\nElapsed Time: " + elapsedTime); | |
} | |
static int RunProgram(string[] args) | |
{ | |
string exe = args[0]; | |
string argLine = null; | |
if (args.Length > 1) | |
{ | |
argLine = args[1]; | |
for (int i = 2; i < args.Length; ++i) | |
{ | |
argLine = argLine + " " + args[i]; | |
} | |
} | |
var process = new Process | |
{ | |
StartInfo = new ProcessStartInfo | |
{ | |
FileName = exe, | |
Arguments = argLine, | |
UseShellExecute = false, | |
RedirectStandardError = true, | |
RedirectStandardInput = true, | |
RedirectStandardOutput = true, | |
CreateNoWindow = true | |
} | |
}; | |
process.OutputDataReceived += OutputDataReceived; | |
process.ErrorDataReceived += ErrorDataReceived; | |
process.Start(); | |
process.BeginOutputReadLine(); | |
process.BeginErrorReadLine(); | |
process.WaitForExit(); | |
return process.ExitCode; | |
} | |
static void OutputDataReceived(object o, DataReceivedEventArgs args) | |
{ | |
Console.WriteLine(args.Data); | |
} | |
static void ErrorDataReceived(object o, DataReceivedEventArgs args) | |
{ | |
if (!string.IsNullOrEmpty(args.Data)) | |
Console.WriteLine("ERROR: " + args.Data); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment